Binding to global variables in Polymer

 ̄綄美尐妖づ 提交于 2019-12-24 15:25:26

问题


I am fairly new to Polymer, and only just studied how data binding works. I am porting an existing Dojo application, where there would be:

1) A single store (holding data) for each URL

2) A message from the server when a store element was updated

As a result, a dynamically made select box which depended on data in the store would automagically have an extra item if anywhere in the application a user added an item to the store (which held the data)

I am trying to replicate something like this in Polymer.

Use case: imagine an URL like this: /app/categories. By querying it with an HTTP GET, you end up with a JSON of all the categories available. While the app is running, the server might notify of a new element in /app/categories. as a result, all of the selects in the application would then have the extra item automagically.

In Polymer, I learned how to bind a property in the current element to a property in a contained element. I understand how this happens with the right events being fired etc. So, the idea would be to create a select where the items are generated by a dom-repeat, which would be bound to... a somehow global variable (?).

But... is it even possible to bind the property of a contained element to a "global" variable, rather than a property of the containing element?

OR, more broadly, is there a pattern (or even an established pattern) to make sure that when a global variable is changed (thanks to a comet message, or whatever), a bunch of elements binding to it will be notified and therefore changed (in this case, the "select" using dom-repeat to show the items!)

Here is a JSBin that shows how to create a menu via iron-ajax At this point what's missing to the JSBin is the simulation of a server push about a data change, as well as a way to have all of the menus update at the same time.


回答1:


IMHO the most sane and maintainable pattern is a one way data flow approach (something along the lines of Flux or Redux (which is a bit simpler).

There is one global state object that exists as as a graph structure and the data flows down your component tree (starting with the root component).
Each component has well defined input properties and receives data from the parent component (using data-binding) and passes on parts of the data to its children. When a component changes state, it fires an event which bubbles up the component tree up to your root component that can then update your global state object (which again flows down your component tree), communicate with the backend, etc.

I can also recommend this video from the Polymer 2015 summit, which explains a similar approach (mediator pattern).



来源:https://stackoverflow.com/questions/35532110/binding-to-global-variables-in-polymer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!