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

I have links that I want to make in different ways depending on the link. Therefore, I have a data structure:

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

Currently in the view, I have a run function that takes an element and does eval (item.onClick), and it works, it just feels like a security hole. I could put onClick in html when rendering the view, but this seems to be wrong.

Does anyone know how to do this?

+4
source share
3 answers

You can embed a function in data

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

You can look here for more useful material on how to do this.

+3
source

Macroblock views have the delegateEvents function:

 var MyView = Backbone.View.extend({ events: { "click button[name='foo']": "baz", "click button[name='bar']": "bam" }, baz: function(){ ... } bam: function(){ ... } 
+3
source

Easy - even if you do not implement an object container to call a function.

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

And assuming you have this as your JSON callback:

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

Source: https://habr.com/ru/post/1382232/


All Articles