Ember属性和javascript链接

ember properties and javascript chaining

本文关键字:链接 javascript 属性 Ember      更新时间:2023-09-26

查看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();

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

如果你查看Ember源代码,你会发现Function原型被扩展为包含property方法。

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

深入观察,我们看到Ember.computed返回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;

因此,无论何时写入

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

你实际上是创建一个匿名函数,然后立即调用它的property方法,返回Ember.ComputedProperty的实例。这是分配给foo属性的内容