akrymski/espresso.js

Using a model function (instead of an attribute)

Closed this issue · 5 comments

Hi, I have a function 'status' on a model that returns the status of an object based on some other model attributes (assigned_to, start_date, complete_date).

In my render function, I'm trying to do this:
render: function() {
return {
job_status: this.model.status
}

However, in my view I just see the toString of the 'status' function (rather than the return value of the function).

In the docs, it says that Model#get accepts an attribute or function name.

What am I doing wrong?

No matter - I think I worked it out. Inside my render function, I actually need to call this.model.status():

render: function() {
  return {
    status: this.model.status()
  }
}

However, I'm still not 100% clear what the documentation means by this:

get get(attr)
attr can be a function name or attribute name

It means you can also do this: model.get("status")

It means you can also do this: model.get("status")

And get what? The toString of the function?

var Car = Espresso.Model.extend({
  status: function() { return "idle" }
});
var c = new Car({a: 1});
console.log(c.get("status"));
//prints: function () { return "idle" }

Sorry my bad, that was old behaviour which has since been changed. the get() function is only needed if you want to make use of the defaults in the model. Otherwise you can access the properties directly, including calling any functions. I'll fix up the docs.

It's easy to have the get('status') check if its a function and execute it, but I haven't come across a case where that's necessarily more convenient than doing model.status() - which is also clearer imo.