在分解Backbone.js的set方法时避免作用域陷阱

Avoiding scope pitfalls when breaking up Backbone.js set method?

本文关键字:作用域 陷阱 方法 set 分解 Backbone js      更新时间:2023-09-26

我使用的是Backbone.js的MVC。

在我的Model.set()方法中,我想在触发更改事件之前等待数据加载。

//Pseudo
set() {
   create changed attributes ... then:
   dataHelper.load(changedAttributes, stabilizeModel)
}
stabilizeModel() {
   now set changedAttributes on model ...
   ... and trigger change events
}

稳定化模型方法的正确方法是:
1)可以访问changedAttributes
2)有正确的范围(被称为从"dataHelper"回调)

我不认为你应该试图覆盖model.set()。相反,你应该利用它:

function load() {
    var attr_to_load = { ... }; 
    var attr = dataHelper.load(attr_to_load );
    this.set(attr);
}

我需要更多的信息才能给你更好的答复。