0

This is not a question regarding nested Views, I have read tutorials on this but they don't seem to apply to my problem.

So: I have a Backbone View that in its render() method creates a totally new and independent element via an external npm module. This not ideal but faster than to rewrite it myself. Within render() and after instantiating the new element I call this.setElement to bind the View to the newly created element. So far so good, this.$el is correctly updated.

But I have defined an events map, whose event handlers don't get moved to the new $el. Why is that? What am I doing wrong?

Ich have created a simplified gist: https://gist.github.com/4nduril/dab571e876b215e3786f

EDIT: I have edited the fiddle of James Akwuh to one resembling my code: https://jsfiddle.net/ztwz3e3o/ You can see, I am calling the render method in an event listener. This fiddle works apparently. So I have still no idea why my own code doesn't.

I'll keep digging.

4nduril
  • 279
  • 1
  • 10
  • I believe this question is answered here: http://stackoverflow.com/questions/9586279/using-setelement-with-views-in-backbone... probably a duplicate question – Jim Edelstein Feb 22 '16 at 14:57
  • Thank you, but I don't think that this is the same problem as I have. As I said, the reference this.$el is updated correctly, but the event listeners are not. If I am misunderstanding your hint, please elaborate. – 4nduril Feb 22 '16 at 15:30
  • I think the issues is that you can't set el inside render, because the view hasn't been rendered yet, so the events can't be maintained. Either append the new elements to an existing element which serves as your el, or try doing this after render. – Jim Edelstein Feb 22 '16 at 15:39
  • Please provide the code in question. – T J Feb 23 '16 at 04:43

2 Answers2

1

Guess you forgot to call render function.

Check working JSFiddle.

James Akwuh
  • 2,169
  • 1
  • 23
  • 25
  • @4nduril In your gist there are too much typos. Moreover there is no `myClickHandler`. Please, provide full code. But anyway, in provided JSFiddle you could see that setElement works perfect. – James Akwuh Feb 23 '16 at 09:38
  • Yes, the gist was insufficient. Therefore I forked your fiddle to and linked to it in my edit. ;) But thank you anyway für your contribution. I have found the solution: see my own answer. – 4nduril Feb 23 '16 at 10:17
0

I have found it and I apologize for not providing enough information for you all to find my error.

The handler function, which I tried to bind with

events: {
    "click": "myHandler"
}

wasn't defined within the view itself (i.e. in the Backbone.View.extend()-call) but in the outer scope. So when I changed "click": "myHandler" to

"click": function () {
    myHandler();
}

it worked like a charm.

4nduril
  • 279
  • 1
  • 10