user2873816
user2873816

Reputation: 179

How to assign delegate events to particular Dom elements

I want to specify click event to particular textfield in my web page, it's id value is service.

Even If I pass another element using setElement() to view, still I want to apply that click event on text-field(id:service).

view code:

var addService=Backbone.View.extend({
    events:{
        "click #service":"alertfunction"
    },
    alertfunction:function(event){
        alert("working");
    }
});
var addFunctionObj=new addService({el:$("div")});

html code:

<div align="center" id="div2">
    <input type="text" id="service" style="width: 200px; height: 20px; color: white; background: green" placeHolder="Enter Service"/>
    <input type="text" id="price" style="width: 200px; height: 20px; color: white; background: green" placeHolder="Enter Price"/>
    <input type="button" id="add" align="center" style="width: 100px; height: 50px; color: white; background: green" value="AddService"/>
    <span>I am Normal Text</span>
</div>

testcases :

Initially If I click on text-field(service),getting alert even If you pass div to view. But If I pass the following names to view using setElement,click event is not working on text-field(service).

view.setElement('#add')
view.setElement('input')
view.setElement('span')

again If you pass div or #div2 to view, click event is working fine on text-field(service).But If you pass the above elements to view,it's not working. Why?

What I want : If you pass any element to view,click event should be work on text-field(service). Is it possible.

Thanks.

Upvotes: 2

Views: 90

Answers (1)

Jacob T. Nielsen
Jacob T. Nielsen

Reputation: 2978

What you are trying to do is not how Backbone works.

What the following code does is listen for click events for children of the "this.el" that bubble up.

events:{
    "click #service": "alertfunction"
}

This means that you cannot set "this.el" to be input#add because this element has no children with the id #service.

Works

<div id="div1">
    <input type="text" id="service" />
</div>

var addFunctionObj=new addService({el:$("div1")});

Does not work

<div id="div1">
</div>
<input type="text" id="service" />

var addFunctionObj=new addService({el:$("div1")});

The second examples does not work because #service is not a child of this.el. As long you "pass" it an element that does not have #service as a child element then it will never work.

Upvotes: 2

Related Questions