简体   繁体   中英

How can I have links which do different things in Backbone.js without using eval()?

I have links which I want to do different things depending on the link. Therefore I have a datastructure:

var data = [{"name":"foo", "onClick":"baz()"}, {"name":"bar", "onClick":"bam()"}];

Currently, in the view i have a function run which takes the item and does eval(item.onClick), and that works, just it feels like a security hole. I could put the onClick into the html when rendering the view, but that feels wrong.

Does anyone know of a way to do this?

You can embed function in the data

var data = [{"name":"foo", "onClick":baz}, {"name":"bar", "onClick":bam}];
item.onClick();

You can look here for more helpful stuff how to do it

Backbone views have a delegateEvents function :

var MyView = Backbone.View.extend({

  events: {
    "click button[name='foo']": "baz",
    "click button[name='bar']": "bam"
  },


  baz: function(){ ... }

  bam: function(){ ... }

Easy -- even if you don't implement an object container for your function call.

function baz(){ 
    ....
}
function bam(){ 
    ....
}

And, assuming you have this as your JSON callback:

function jsonCallback(data){
    /*some code*/
    window[data.onClick]();
    /* some more code */
} 

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