mikeric / rivets

Lightweight and powerful data binding.
http://rivetsjs.com
MIT License
3.23k stars 310 forks source link

rv-data-* gotcha with jQuery #692

Closed ghost closed 7 years ago

ghost commented 7 years ago

This isn't technically an issue / bug because Rivets is independent of jQuery but I did run across a subtle gotcha that manifests itself as a bug if you are using jQuery and Rivets together. So I want to document my finding here so if anyone else runs into this problem, they can get a quick answer and save some time.

This problem can manifest itself if you have multiple elements on the screen and are using data-id to identify the elements for events. I was seeing buttons that appeared to have the correct data-id set however, when I queried the element with jQuery with the .data() function I got an incorrect (yet still valid) value.

You cannot rely on rv-data-* using rv-* default attribute binder if you expect jQuery to consume the data-* attribute on the element later with the .data() function. This is because jQuery caches data parameters accessed with .data() the first time you set the value of that attribute. Rivets however sets the attribute on the element with rv-* but (of course) it doesn't update jQuery's cache and jQuery itself will not update it's cache for data parameters.

See this post for a better explanation: https://stackoverflow.com/questions/28335833/get-wrong-value-in-data-attribute-jquery

The fix: Create your own binder for rv-data-* which sets the data parameter via jQuery. Something like the following will work (although it can be generalized).

rivets.binders["data-id"] = function(el, value) { $(el).data('id', value); }

Hopefully, this will save someone some time down the road. :)

Namek commented 7 years ago

@kitanata Seems to be the exact same topic - https://github.com/mikeric/rivets/issues/684

You cannot rely on rv-data-* using rv-* default attribute binder if you expect jQuery to consume the data-* attribute on the element later with the .data() function.

I think you stated things the opposite way. You shouldn't rely on jQuery on this matter.

benadamstyles commented 7 years ago

@Namek Should we add this to the docs? @jccazeaux I still don't fully understand what the process is to contribute to docs – could you add that to the readme perhaps? Thanks!

Namek commented 7 years ago

TBH I don't know but in some places even mentioning jQuery is evil so no :)

I believe rivets should have nothing to do with jQuery at all. If anyone would have same problem he/she should be able to find at least two topics on these Issues pages already. I suggest closing.