gpt4 book ai didi

javascript - Backbone.js 模型与 View 集

转载 作者:行者123 更新时间:2023-11-29 22:24:47 24 4
gpt4 key购买 nike

如果我使用的是 Backbone,哪一个(或两个)是设置数据的“正确”方式?

// Logic in the Model
// Can call from anywhere that has access
SomeModel = Backbone.Model.extend({
defaults: {
visible: false
},

toggle: function(visible){
visible = typeof visible !== "undefined" ? visible : !this.get("visible");
this.set({visible: visible});
}
});

// Logic in the View
SomeView = Backbone.View.extend({
events: {
"click .toggle" : "toggleVisibility"
},

toggleVisibility: function(){
this.model.set({visible: !this.model.get("visible")});
}
});

显然,其中任何一个都有效,但我的问题是应该将多少逻辑推给模型?例如,如果我遇到更新两个变量的情况:

this.model.set({visible: false, foo: bar, something: else});

像这样在模型上创建一个函数是否有意义:

someFunction: function(visible, foo, something){
this.set({visible: visible, foo: foo, something: something});
}

这对我来说似乎有点矫枉过正,但 View 中的 set({}) 逻辑感觉很脏。

想法?

最佳答案

我会让切换函数成为模型的一个成员,并从您的 View 中调用它,隐藏实现细节。请记住,一个模型一次可以由多个 View 表示,因此任何通用模型逻辑都应该集中在那里。

也许是这样的:

// Logic in the Model
// Can call from anywhere that has access
SomeModel = Backbone.Model.extend({
defaults: {
visible: false
},

toggle: function(visible){
visible = typeof visible !== "undefined" ? visible : !this.get("visible");
this.set({visible: visible});
}
});
OR

// Logic in the View
SomeView = Backbone.View.extend({
initialize: function() {
this.model.bind('change:visibility',this.changeVisibility);
}
events: {
"click .toggle" : "toggleVisibility"
},

toggleVisibility: function(){
this.model.toggle();
}
changeVisibility: function() {
........
/// seems like alot of extra work to get to this point
/// but remember, all views for the model are will receive this
/// event now, not just the one that received the UI click
/// whether or not that's the behavior you want is up to you.
........
}
});

关于javascript - Backbone.js 模型与 View 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10228591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com