javascript - Updating cloned element when original Element is modified -
i new jquery , enjoy few leads put me on right track :)
issue: have cart total price shown on place of page clone() , have cloned price auto-update each time original price element modified.
jquery("document").ready(function($){ var $vartocopy = $('#totalpricemodule').clone(true); $('.column42').append($vartocopy); });
there several approaches can take facing issue. however, there 1 thing sure, javascript not provide magic require here , jquery neither.
1. move data-centric thinking(reactive)
long story short, problem originates in fact don't have single source of truth(wiki) price. means displaying 2 different prices have same value because mean them to. 2 prices have 2 representations in memory of program , fact causes problems have.
data-centric approach in case - or reactive thinking people prefer - storing price in js variable/object/whatever(or speaking store in memory of js program instead of dom) , @ 1 place. now, whoever , whatever wants display or use value needs access variable/object/whatever.
i believe misconception many js developers have js code not program, it's sugar coat on dom(and jquery doesn't mitigate this). in opinion it's wrong. 1 should use dom displaying things browsers do. so, store data in memory, use js running code , display things via dom.
there many libraries out there can make work without difficulty. however, not without cost. firstly, need learn new library, secondly have yet dependency , thirdly makes site more dependant on js itself. though, it's worth it. if sake of being better programmer.
the library want recommend vue. not without reason. vue easy learn, lightweight, fast, doesn't force on "framework" , has decent documentation. of course of possible because core of vue not feature-rich other libraries believe it's perfect needs now.
with vue can hold price in 1 variable , whenever update variable places used updated automatically. think magic want.
2. create function update value
create function updateprice update places need updated. how hold references you. if there several places can update them explicitly. though, assumes there 1 price display. if there many different prices i.e. products list gets harder. in end might end reinventing wheel , create similar vue , other such libraries have offer.
3. eliminate problem without solving it
you can decide need price displayed @ 1 place eliminating problem itself. without problem there nothing solve.
Comments
Post a Comment