简体   繁体   中英

Backbone View custom events

I want to validate a users input by keydown. For this I require a keydown event. Unfortunatly I only have found custom model events:

initalize: function(){
    this.model = new ModelClass();
    this.model.bind("keydown", this.validate, this);
}

That approach surely is fine for model events but I don't believe this is the right way for view, ui-related stuff...

To give you a better explication, this is how I would like to use my event:

var SomeView;

SomeView = Backbone.View.extend({
    events: {
        "keydown input#some-field": "validate" // custom event
        , "change input#some-field": "doSomethingElse" // predefined backbone event
    },
    validate: function(attr){
        // validation
    }
});

So what is the approach to create custom Backbone Events which are callable in the View?

what is the approach to create custom Backbone Events which are callable in the View? I feel as if your problem is not a problem,because backbone.view default has been to support the events. you can write code like what you want to:

//This is the right thing to do
SomeView = Backbone.View.extend({
    events: {
        "keydown input#some-field": "validate" // custom event
        , "change input#some-field": "doSomethingElse" // predefined backbone event
    },
    validate: function(attr){
        // validation
    }
});

Reference here: http://backbonejs.org/docs/todos.html#section-22

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

EDIT : you can see here: http://backbonejs.org/docs/backbone.html#section-156

The most critical sentence is:

this.$el.delegate(selector, eventName, method);

because backbone's events is jquery's delegate(http://api.jquery.com/delegate/),so jQuery's delegate to support the event, backbone are available.

I'm not sure I'm understanding what the problem is. Your second example is definitely how I would and have gone about setting up event handlers in Backbone Views. Backbone's validate method only exists in the model and is called automatically before the models set and save are called. It is left undefined as default. If you are validating in the view though your way should work. But i believe event handling functions are only passed the event. so it should probably be

validate: function (event) {
   // do Something here
}

also you should keep in mind that backbone event delegation takes place in the el. so you will need to either set it manually or render into it in order for event delegation to to work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM