code

Backbone의 모델을 초기 기본값으로 재설정하는 가장 쉬운 방법은 무엇입니까?

codestyles 2020. 12. 7. 08:10
반응형

Backbone의 모델을 초기 기본값으로 재설정하는 가장 쉬운 방법은 무엇입니까?


내 모델에는 이미 defaults해시가 있습니다. 보기 / 페이지의 일부가 재설정되면 모델을 원래 기본값으로 재설정하고 싶습니다.

현재는 명시 적으로 각 속성을 기본값으로 설정합니다. 단일 명령문에서이 작업을 수행하는 데 사용할 수있는 내장 또는 JavaScript / Underscore.js / Backbone.js / jQuery 함수가 있습니까?


myModel.clear().set(myModel.defaults);

모델에 null이 아닌 초기 개체 속성이있을 때이 작업을 수행합니다.

먼저 기본값 을 함수로 정의

var MyModel = Backbone.Model.extends({

    defaults:function(){

        return {
            AnArrayTypeProp:[]
        };
    }

});

둘째, 모델을 기본값으로 재설정해야 할 때

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

다음과 같은 접근 방식을 생각해 냈습니다.

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

{silent: true}clear()것을 호출 보장하지만 change이벤트가 발생하지 않습니다; set()호출 시에만 화재가 발생합니다 .


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 자체를 확장 할 수 있습니다.

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

면책 조항 : JavaScript lib 또는 Backbone 플러그인을 작성하는 경우이 작업을 수행하지 마십시오. 다른 lib와 충돌 할 수 있거나 코드를 사용하는 사람이 예상 한 것과 다른 동작을 일으킬 수 있습니다.


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.


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

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

My solutions is:

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

참고URL : https://stackoverflow.com/questions/6889457/easiest-way-to-reset-backbones-model-to-initial-defaults

반응형