4

I am trying to assign a function to a property on bunch of elements using .prop()

$('.whatever').prop({MyProp:MyFunc});

Looking closely at the documentation for this function it seems there is a special behaviour where the value is a function and the property will NOT be assigned the function but rather the functions return value.

Is there a simple workaround for this or should I just use

$('.whatever').each(function(id, item){item.MyProp=MyFunc;});
DJL
  • 1,821
  • 3
  • 17
  • 31
  • Why would you want to assign a function to a DOM property? For event handler properties there are better alternatives. – Bergi Jul 16 '13 at 11:18
  • My function is not an event handler but a method. It is called to DO something not because something has happened – DJL Jul 16 '13 at 11:39
  • But what is it doing in the DOM then? Place it somewhere else. – Bergi Jul 16 '13 at 11:50
  • Where? The functionality is intrinsically linked to the element. Putting it anywhere else makes no logical sense. Having some kind of dictionary lookup for the sake of it also makes no sense. – DJL Jul 16 '13 at 15:19
  • What exactly are you trying to approach? If we know what you're trying to do, we will be able to help you better. There are very few cases where the logic needs to be accessible from the DOM, usually it's the other way round. There are some design patterns for jQuery to work around [extending the dom](http://perfectionkills.com/whats-wrong-with-extending-the-dom/). – Bergi Jul 16 '13 at 15:26
  • I read that article from start to finish and I now understand why this is considered a bad idea. In fact I would say that the .prop method should fail on all properties that aren't already defined AND it should explain in the documentation why this is the case. Thanks @Bergi – DJL Jul 17 '13 at 08:50

1 Answers1

1

.prop() is not for such purpose. That's why you have the .data() method.

$('.whatever').data('MyFunc', MyFunc);

// somewhere else:
var MyFunc = $('.whatever').data('MyFunc');
MyFunc(args);
gustavohenke
  • 38,209
  • 13
  • 113
  • 120
  • Unfortunately this means the calling code needs to use the .data method also. Whereas using a property has no such requirements item.MyProp(); – DJL Jul 16 '13 at 11:38
  • Don't attach things to DOM elements. Depending on what your property name is, it may affect the functionality of your element. – gustavohenke Jul 16 '13 at 12:07