开发者

how do I use variables when binding backbone view events?

开发者 https://www.devze.com 2023-04-09 05:36 出处:网络
I want to bind an eve开发者_开发问答nt to a view using a selector I define in the view\'s options.

I want to bind an eve开发者_开发问答nt to a view using a selector I define in the view's options.

Something like (in coffescript):

events: ()->
  "change" : "setNewCheckedStateWithCheckbox"
  '"click'+ @.options.choices_button_selector +'"' : "test"

Can't for the life of me figure it out.


The problem here is that you can't do expressions in the keys of JavaScript object literals. The only way to set arbitrary keys on objects it to use the obj[expression] syntax.

Here's one way to rewrite your code to do what you want:

class MyView extends Backbone.View
  _events = change: "setNewCheckedStateWithCheckbox"
  events: ->
    eventsHash = _.extend {}, _events
    eventsHash["click #{@.options.choices_button_selector}"] = "test"
    eventsHash


try this

events: ()->
  "change" : "setNewCheckedStateWithCheckbox"
  "click#{@options.choices_button_selector}" : "test"

next time just stick in a console.log to display values you're not sure about.

console.log '"click'+ @.options.choices_button_selector +'"'

that would output "click#selector" with the quotes (that shouldn't be there).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号