将 Backbone 模型重置为初始默认值的最简单方法?

发布于 2024-11-26 23:12:57 字数 173 浏览 0 评论 0原文

我的模型已经有一个 defaults 哈希值。当部分视图/页面被重置时,我希望将模型重置回原始默认值。

目前,我明确地将每个属性设置为其默认值。是否有任何内置功能或 JavaScript/Underscore.js/Backbone.js/jQuery 函数可以用来在单个语句中执行此操作?

My models already have a defaults hash. When parts of the view/page are reset, I wish to reset the models back to their original defaults.

Currently, I explicitly set each attribute to its default value. Is there anything built in or a JavaScript/Underscore.js/Backbone.js/jQuery function that I could use to do this in a single statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

人│生佛魔见 2024-12-03 23:12:57
myModel.clear().set(myModel.defaults);
myModel.clear().set(myModel.defaults);
热血少△年 2024-12-03 23:12:57

我想出了以下方法:

reset: function () {
    this.clear({silent: true});
    this.set(this.defaults);
}

clear() 调用中使用 {silent: true} 可确保不触发 change 事件;它只会在 set() 调用时触发。

I came up with the following approach:

reset: function () {
    this.clear({silent: true});
    this.set(this.defaults);
}

Having {silent: true} in the clear() call ensures that the change event is not fired; it will be fire only on set() call.

七度光 2024-12-03 23:12:57

当模型具有非空初始对象属性时,我会执行此操作。

首先,将 defaults 定义为函数

var MyModel = Backbone.Model.extends({

    defaults:function(){

        return {
            AnArrayTypeProp:[]
        };
    }

});

,其次,在需要时将模型重置为默认值

model.clear().set(model.defaults());

I do this when the model has non-null initial object properties.

first, define defaults as a function

var MyModel = Backbone.Model.extends({

    defaults:function(){

        return {
            AnArrayTypeProp:[]
        };
    }

});

second, when needed to reset model to default

model.clear().set(model.defaults());
黑色毁心梦 2024-12-03 23:12:57

基于 saabeilin 的回答和 Backbone 的注释源,我提供了一个最佳函数来满足重置模型的需要。

可重用重置

/**
 * Clears the model's attributes and sets the default attributes.
 * @param  {Object} attrs to overwrite defaults
 * @param  {Object} options  to pass with the "set" call.
 * @return {Backbone.Model}  this object, to chain function calls.
 */
reset: function(attrs, options) {
    // adds default option reset to true
    options = _.extend({ reset: true }, options);

    // ensure default params
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

    // apply
    this.clear({ silent: true }).set(attrs, options);

    // triggers a custom event, namespaced to model in order
    // to avoid collision with collection's native reset event
    // when listening to a collection.
    if (!options.silent) this.trigger('model:reset', this, options);

    return this;
},

以下行确保即使属性作为 undefined { test: undefined } 传递,它仍然具有默认值。

attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

下面是一个示例:

var defaults = { test: 1 }, 
    attrs = { test: undefined };

_.extend({}, defaults, attrs);                       // {test: undefined}
_.defaults(_.extend({}, defaults, attrs), defaults); // {test: 1}

扩展 Backbone

如果您希望将它用于所有 Backbone 模型,您可以扩展 Backbone 本身:

_.extend(Backbone.Model.prototype, {
    reset: function(attributes, options){
        /* ... */
    }
});

免责声明:如果您正在编写 JavaScript 库或 Backbone 插件,请不要这样做,因为它可能会这样做与另一个库发生冲突,否则可能会导致与使用您的代码的人预期不同的行为。

Based on saabeilin's answer and Backbone's annotated source, I came with an optimal function to fill the need for resetting a model.

Reusable reset

/**
 * Clears the model's attributes and sets the default attributes.
 * @param  {Object} attrs to overwrite defaults
 * @param  {Object} options  to pass with the "set" call.
 * @return {Backbone.Model}  this object, to chain function calls.
 */
reset: function(attrs, options) {
    // adds default option reset to true
    options = _.extend({ reset: true }, options);

    // ensure default params
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

    // apply
    this.clear({ silent: true }).set(attrs, options);

    // triggers a custom event, namespaced to model in order
    // to avoid collision with collection's native reset event
    // when listening to a collection.
    if (!options.silent) this.trigger('model:reset', this, options);

    return this;
},

The following line ensures that even if an attribute is passed as undefined { test: undefined }, it'll still have its default value.

attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

Here's an example:

var defaults = { test: 1 }, 
    attrs = { test: undefined };

_.extend({}, defaults, attrs);                       // {test: undefined}
_.defaults(_.extend({}, defaults, attrs), defaults); // {test: 1}

Extending Backbone

And if you want it with all Backbone models, you can extend Backbone itself:

_.extend(Backbone.Model.prototype, {
    reset: function(attributes, options){
        /* ... */
    }
});

Disclaimer: Don't do this if you're writing a JavaScript lib or Backbone plugin, as it could collide with another lib or it could cause a different behavior than the one expected by the person using your code.

再可℃爱ぅ一点好了 2024-12-03 23:12:57

我还考虑过结合使用 model.clear()model.set() 。然后我遇到了问题,我现在触发了 change 事件两次。
调用 model.clear() 时使用 silent 选项不是一个选项,因为我还希望在属性被取消设置。

我最终添加了一个 model.reset() 方法。它采用新的属性哈希,并使用新属性哈希中不存在的旧属性键的未定义值填充该哈希。

Model.prototype.reset = function(attrs, options) {
    for (var key in this.attributes) {
        if (key in attrs) continue;
        attrs[key] = void 0;
    }

    return this.set(attrs, options);
};

通过这种方式,您可以重置模型的旧属性,并为每个旧属性和新属性获取有效的 change 事件。

I also thought about using model.clear() and model.set() in conjunction. Then I ran across the problem, that I trigger the change event twice now.
Using the silent option when calling model.clear() is not an option, because I also want to have a change event fired, when a property gets unset.

I ended up with adding a model.reset() method. It takes a new attributes hash and fills this hash with undefined values for old attributes keys not being present in the new attribute hash.

Model.prototype.reset = function(attrs, options) {
    for (var key in this.attributes) {
        if (key in attrs) continue;
        attrs[key] = void 0;
    }

    return this.set(attrs, options);
};

This way you reset the models old attributes and get a valid change event for every old and new attribute.

孤檠 2024-12-03 23:12:57

用新的空模型覆盖当前模型的值怎么样:

myModel = new model(); // default values will be considered

What about overriding the value of current model with a new empty model :

myModel = new model(); // default values will be considered
两相知 2024-12-03 23:12:57

我的解决方案是:

model.clear({silent: true}).set(model.defaults);

My solutions is:

model.clear({silent: true}).set(model.defaults);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文