2

查看 ember.js 文档(http://emberjs.com/guides/object-model/computed-properties/)我了解如何使用属性,但之前没有在对象声明中运行过链式方法。

在我看来,该property方法应该立即被调用,但事实并非如此。

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: function() {
    var firstName = this.get('firstName');
    var lastName = this.get('lastName');

   return firstName + ' ' + lastName;
  }.property('firstName', 'lastName')
});

var tom = Person.create({
  firstName: "Tom",
  lastName: "Dale"
});

tom.get('fullName') // "Tom Dale"

如果我制作一个小的 js 片段,这里似乎什么都做不了。 http://jsfiddle.net/xXStr/

var a = {
    what: function() {
        alert ("oh yeah");
    },
    bar: function() {
        alert ("bar");
        return this;
    }.what()
}
a.bar();

对象声明中的链式方法如何工作?

4

1 回答 1

1

If you look inside the Ember source, you will find that the Function prototype is extended to include a property method.

Function.prototype.property = function() {
  var ret = Ember.computed(this);
  return ret.property.apply(ret, arguments);
};

Looking deeper, we see that Ember.computed returns an instance of Ember.Computed.

Ember.computed = function(func) {
  var args;

  if (arguments.length > 1) {
    args = a_slice.call(arguments, 0, -1);
    func = a_slice.call(arguments, -1)[0];
  }

  var cp = new ComputedProperty(func);

  if (args) {
    cp.property.apply(cp, args);
  }

  return cp;
};

// ...

function ComputedProperty(func, opts) {
  this.func = func;
  this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : true;
  this._dependentKeys = opts && opts.dependentKeys;
}

Ember.ComputedProperty = ComputedProperty;

Thus, whenever you write

foo: function() {
  return this.get('bar')
}.property('bar')

you are actually creating an anonymous function and then immediately invoking its property method, returning an instance of Ember.ComputedProperty. This is what gets assigned to the foo property.

于 2013-03-04T18:04:21.623 回答