What is 'vending' in React Native? - reactjs

After reading through some of the React Native docs I was left wondering where the term 'vend' comes from. Can anyone elucidate the etymology of 'vend' or whether the word could benefit from a more expansive definition than the procedural one given in the docs (this one is from the React Native iOS docs):
Vending a view is simple:
Create the basic subclass.
Add the RCT_EXPORT_MODULE() marker macro.
Implement the -(UIView *)view method

In this case, vend is synonymous with 'serve'. Try replacing each instance of 'vend' with 'serve' and it should make sense to you.
The key is to make the RCTMapManager a delegate for all the views it vends, and...
.
You can see we're setting the manager as the delegate for every view that it vends, then...
.
These subclasses are similar in function to view controllers, but are essentially singletons - only one instance of each is created by the bridge. They vend native views to the RCTUIManager, which...

Related

React Simple Global Entity Cache instead of Flux/React/etc

I am writing a little "fun" Scala/Scala.js project.
On my server I have Entities which are referenced by uuid-s
(inside Ref-s).
For the sake of "fun", I don't want to use flux/redux architecture but still use React on the client (with ScalaJS-React).
What I am trying to do instead is to have a simple cache, for example:
when a React UserDisplayComponent wants the display the Entity User with uuid=0003
then the render() method calls to the Cache (which is passed in as a prop)
let's assume that this is the first time that the UserDisplayComponent asks for this particular User (with uuid=0003) and the Cache does not have it yet
then the Cache makes an AjaxCall to fetch the User from the server
when the AjaxCall returns the Cache triggers re-render
BUT ! now when the component is asking for the User from the Cache, it gets the User Entity from the Cache immediately and does not trigger an AjaxCall
The way I would like to implement this is the following :
I start a render()
"stuff" inside render() asks the Cache for all sorts of Entities
Cache returns either Loading or the Entity itself.
at the end of render the Cache sends all the AjaxRequest-s to the server and waits for all of them to return
once all AjaxRequests have returned (let's assume that they do - for the sake of simplicity) the Cache triggers a "re-render()" and now all entities that have been requested before are provided by the Cache right away.
of course it can happen that the newly arrived Entity-s will trigger the render() to fetch more Entity-s if for example I load an Entity that is for example case class UserList(ul: List[Ref[User]]) type. But let's not worry about this now.
QUESTIONS:
1) Am I doing something really wrong if I am doing the state handling this way ?
2) Is there an already existing solution for this ?
I looked around but everything was FLUX/REDUX etc... along these lines... - which I want to AVOID for the sake of :
"fun"
curiosity
exploration
playing around
I think this simple cache will be simpler for my use-case because I want to take the "REF" based "domain model" over to the client in a simple way: as if the client was on the server and the network would be infinitely fast and zero latency (this is what the cache would simulate).
Consider what issues you need to address to build a rich dynamic web UI, and what libraries / layers typically handle those issues for you.
1. DOM Events (clicks etc.) need to trigger changes in State
This is relatively easy. DOM nodes expose callback-based listener API that is straightforward to adapt to any architecture.
2. Changes in State need to trigger updates to DOM nodes
This is trickier because it needs to be done efficiently and in a maintainable manner. You don't want to re-render your whole component from scratch whenever its state changes, and you don't want to write tons of jquery-style spaghetti code to manually update the DOM as that would be too error prone even if efficient at runtime.
This problem is mainly why libraries like React exist, they abstract this away behind virtual DOM. But you can also abstract this away without virtual DOM, like my own Laminar library does.
Forgoing a library solution to this problem is only workable for simpler apps.
3. Components should be able to read / write Global State
This is the part that flux / redux solve. Specifically, these are issues #1 and #2 all over again, except as applied to global state as opposed to component state.
4. Caching
Caching is hard because cache needs to be invalidated at some point, on top of everything else above.
Flux / redux do not help with this at all. One of the libraries that does help is Relay, which works much like your proposed solution, except way more elaborate, and on top of React and GraphQL. Reading its documentation will help you with your problem. You can definitely implement a small subset of relay's functionality in plain Scala.js if you don't need the whole React / GraphQL baggage, but you need to know the prior art.
5. Serialization and type safety
This is the only issue on this list that relates to Scala.js as opposed to Javascript and SPAs in general.
Scala objects need to be serialized to travel over the network. Into JSON, protobufs, or whatever else, but you need a system for this that will not involve error-prone manual work. There are many Scala.js libraries that address this issue such as upickle, Autowire, endpoints, sloth, etc. Key words: "Scala JSON library", or "Scala type-safe RPC", depending on what kind of solution you want.
I hope these principles suffice as an answer. When you understand these issues, it should be obvious whether your solution will work for a given use case or not. As it is, you didn't describe how your solution addresses issues 2, 4, and 5. You can use some of the libraries I mentioned or implement your own solutions with similar ideas / algorithms.
On a minor technical note, consider implementing an async, Future-based API for your cache layer, so that it returns Future[Entity] instead of Loading | Entity.

Episerver - Why BlockData doesn't implement IContent

Does anybody knows why BlockData class doesn't directly implement IContent?
I know that during BlockData is being retrieve from database, proxy created by Castle implements IContent.
If StackOverflow isn't suitable place for this kind of a question, please move it.
Johan Björnfot at EPiServer explains some of the details in this post.
Excerpt:
"In previous versions of CMS was pages (PageData) the only content type that the content repository (traditionally DataFactory) handled. In CMS7 this has changed so now content repository (IContentRepository) handles IContent instances. This means that the requirement for a .NET type to be possible to save/load from content repository is that it implements the interface EPiServer.Core.IContent.
There are some implementations of IContent built into CMS like PageData and ContentFolder (used to group shared block instances) and it is also possible to register custom IContent implementations.If you look at BlockData though you will notice that it doesn’t implement IContent, how is then shared block instances handled?
The answer is that during runtime when a shared block instance is created (e.g. through a call to IContentRepository.GetDefault where T is a type inheriting from BlockData) the CMS will create a new .NET type inheriting T using a technic called mixin where the new generated subclass will implement some extra interfaces (including IContent)."
BlockData does implement IContent as it is intended to work both when added to another content item such as a PageData instance (a.k.a. Local Block), and as a standalone instance (a.k.a.Shared Block). In latter case the interface is added by using a mix-in though Castle Windsor so that it can be referenced.
The decision for this construct was based on wanting to be able to use the same rendering templates regardless if a block is local or shared. Therefor the choice stood between having a large number of empty properties on local blocks or the current solution using mixins. Both options were tested and mixins was selected as the preferred solution even though it's not a perfect one.
BlockData "does implement IContent", just do:
var myContent = (IContent)myBlock;
But, if you're by any chance handling a Block which itself is a property (not a ContentReference), that cast will throw an exception.
This will be true for 100% of all cases (... using Math.Round).

D3 with Backbone / D3 with Angular / D3 with Ember?

I'm working on a medium sized application that is going to include a lot of D3 charts / interactions in it. I'm wondering if anyone has tried to use Backbone, Angular, or Ember with D3, and if so, which one seems like the best fit for a front end MV* framework. The application won't be doing a whole lot of CRUD operations, mainly interactive charts and widgets to manipulate them.
Any comments appreciated!
We used d3 with Backbone pretty extensively on a project that consisted of multiple "scenes". Each scene contained a set of different charts, and a user has the ability navigate from one scene to another. These scenes and their content all needed to be highly configurable (e.g. label colors and formatting, or indicating which data params should be plotted on a given axis).
D3 (rightfully) doesn't provide a view management system, which is where Backbone took over. Backbone Views served as wrappers for d3 charts. Predictably, Backbone Models served as the carriers of the d3-plotted data. But more interestingly, we also found that they served well as a means of controlling the appearance and behavior of the d3 code contained within the Backbone Views; essentially they served as view models. Since d3 promotes passing functions as arguments into other functions, these Backbone Models-as-view-models ended up holding many functions in them.
The following is a simplistic example, but picture doing this with dozens of properties. Using coffeescript here, because it's shorter (and better).
First, there's the model, which we instantiate inside (for example) a router's event handler. We populate this model with functions that will be applied to d3 selectors.
barChartModel = new Backbone.Model
barColor: (d, i) -> if d.profits < 0 then "red" else "green"
barLengthVal: (d, i) -> return bar.profits #// profits will be the prop we graph
onClick: (d, i) ->
console.log "We are", if d.profits <= 0 then "losing" else "making", "money"
data: someJsonWeLoaded
We pass this model into a new view:
barChartView = new BarChartView
el: "#the_bar_chart"
model: barChartModel
A view might be implemented like this:
class BarChartView extends Backbone.View
render: ->
bars = d3.select(#el)
.selectAll('.bar')
.data(#model.get 'data') # <---- THIS
bars.enter()
.attr('class', 'bar')
.attr('fill', #model.get 'barColor') # <---- THIS
.attr('height', (d, i) ->
#barLengthScale #model.get('barLengthVal')(d, i) # <---- AND THIS
)
.on('click', #model.get 'onClick') # <---- INTERACTIVITY TOO
initialize: ->
#barLengthScale = d3.scale.linear()
.domain([-100, 100]) # <---- THIS COULD ALSO COME FROM MODEL
.range([0, #$el.height()])
#render()
I have used D3 with Angular on a few dashboards, and it worked very well. I have never really used Backbone, and not with D3, so I cannot compare the two. I chose Angular to complement D3 because it appeared to me that lately the D3 community has been using D3 with Angular the most of the three options you mentioned, so there were great resources available. There has recently been an entire book dedicated to using D3 and Angular together. I had also used Angular a bit before, and was aware of directives. Directives (in Angular it is a way to extend html tags) are great for meshing with D3. Each chart can become a directive, and then makes it extremely easy to reuse charts, changing only the $scope data. These are some resources I found helpful when combining the two:
https://www.youtube.com/watch?v=aqHBLS_6gF8
https://leanpub.com/d3angularjs
http://plnkr.co/edit/WnoCtNPV9azj0oPwv9kM?p=preview
http://vicapow.github.io/angular-d3-talk/slides/demos/a-donut-chart-editor/index.html#/
I recently gave a talk on this very topic, here are some links: Video · Code · Slides
I've done some smaller projects using similar methods to meetamit, but have recently started exploring Ember + D3. I haven't done much yet, but I think Ember has a lot to offer that could simplify building these types of app. Some things that come to mind:
Computed properties: you'll often be displaying aggregates, so slicing your data using computed properties means you just have to call your chart's update function whenever the data changes, and you're good to go. No more worrying about sending off an event to every view that will change when one specific part of your data changes. Plus, these will probably be properties on your controllers, instead of being calculated within a specific chart or view, which will make reuse much easier.
Storing state: I had a tough time figuring out the best way to store state in Backbone. I started out trying to coordinate everything via events, but in the end landed on having a separate State model which acted as the brains of the whole system.
I didn't get around to using Backbone's router much, but Ember's router + focus on state has made this design challenge easier for me so far. If you build within the system, you can click around your filters and controls, and everything just works. It may be possible to do exactly the same thing in Backbone, but there's something to be said for seriously reducing your cognitive load. You can also explicitly use a StateManager object - there may be some really interesting solutions here, though I haven't explored them yet.
Again, my experience with this combo is shallow, but if my instinct is right there are going to be many gains from building visualizations within Ember's conventions.
If you haven't already come across this, Square put up an article briefly covering their experience building an interactive dashboard with Ember + D3.
Keep us up to date on your progress + any insights you come across, and good luck!
My group has used both angular and backbone with d3, and we like both for different reasons.
Backbone
Backbone is a bit less opinionated about the way you construct your application, which is nice if you need to customize the way data is getting handled for performance. You generally integrate d3 with a backbone view.
One challenge of working with Backbone is memory management for complex views, but using marionette helps with that. Also Marionette's event aggregator (and specifically using request-response) is a good fit for centralized data sources for coordinated views if you want to use something like crossfilter or lunr.
Angular
Angular is more structured, and it is allows you to build up cool features very quickly. It has a steep learning curve, but I've found now that I'm understanding angular (having using it to develop an application for the past ~4 weeks), I've found that I can accomplish many of the same things I can in backbone without resorting to anything too hackish.
Like the request-response object in backbone marionette, using angular services allows you to build up complex views quickly. You'll need to avoid using angular's dirty checking on $scope data for complex data visualizations to keep your application from bogging down, so the code you write for working with your data in angular is going to end up looking a lot like the code you would write in backbone.
I had resisted angular's "magic" for a while, but I'm starting to get won over by the speed of development you can achieve because of all the built in directives, scope checking, and other goodies. Angular still allows you to poke around in its internals to speed up your code when that's required. This "digging" may take more time than in backbone (because the code base is more complex), but I've found that time lost in this phase is usually recouped by time saved avoiding common bugs like memory leaks in view code and writing boilerplate code like view rendering and data binding.
In summary
Backbone is a good choice if you need extensive control and customization
Angular is excellent if you really like data binding
Ember is probably fine too, if for no other reason than Square uses (used?) it, and Mike Bostocks worked for Square.
In any framework the "hard" data intensive parts of your app are probably going to look similar if you write them well (i.e. get the data transformations into services and put a clean simple interface around your view code)
D3 on Angular
I use D3 on Angular since one year and I love the combination of both. Angular uses directives to create new and reusable HTML elements. When you have this knowlegde, you can encapsule a D3 visualization in an Angular directive without having D3 in your controllers or somewhere else. After that you can reuse the directive everywhere in your application to visualize your data. When working in a team of multiple Angular developers, the rest of your team doesn't need to know anything about D3, because your D3 code exists only in the directive.
Directives in Angular give you a flexible way of dealing with data. You can choose whether your data persists in your directive (then you will have a static reusable visualizaiton) or you make a data binding to a controller in your Angular application (then you will have a dynamic reusable visualization). The latter can be achieved by setting a scope in your directive
scope: { data: '=' /* bi-directional binding */ },
setting the data in your controller
$scope.data = [23,44,22];
and join both in your HTML element instance
<div your-new-d3-element data="data"></div>.
Thats it!
Furthermore you can use watcher in your directive to watch changing data in your controller. A nice example of reusable d3 directives in Angular gives this example: http://bl.ocks.org/biovisualize/5372077
Moreover you can find an easy D3 on Angular setup in this article: http://goo.gl/hNS8k1
On this site you find further introductions how to use d3-plugins like the fisheye plugin in your Angular application or how to implement more complex d3 visualizations in Angular.
I have worked with Backbone+d3 and with Angular+d3 a little bit.
Backbone suffer with memory leaks problem and if you use backbone you should be accurate with garbage collection. However as mentioned before marionet or chaplin can easily solve this problem. If you want to have light and fast application I recommend you to use react engine for views and backbone models for other needs.
As to Angular it has more strict structure. However, I believe that it will be almost the same logic as Backbone. Angular takes care about architecture and everything what is needed just write code by refs and it will be maintable. Unlike backbone, where structure is your option.
I recommend you to compare routing, bindings, models to select right framework, but not views.
I always choose backbone + smths, often React. Because it is flexible and easy to manage application views. F.e. when we found react we moved from backbone to react to fix our mremory leak problems. However applicarion had about 50 views with different data visualisation tools with many controls. And we moved views step by step in two month.
It is difficult to do same thing with same efforts in angular.
D3 on Angular.js
I think these types of questions don't really have a right answer IMO, it's like asking someone whether they should choose a Subaru or a Toyota, when all they need to do is get from a to b :) Anyway, using AngularJS and D3 at the moment, so far so good :) There is a nice AngularJS directive for D3 and NVD3, if you do choose to go with AngularJS.
Also, check out this excellent post on combining D3 with AngularJS.
Happy exploring!

Loading CakePHP Helpers

This is a multi part question.
Background:
I'm building my first site using CakePHP, and I like it so far. I've got a DB setup, initial data loaded, and a few models, views, and controllers to interface with the data.
I've created a globally accessible function to create Add/Edit/Delete type image links in various areas. It will be used across multiple views, so I need it accessible, essentially, everywhere. The function is defined in /app/config/bootstrap.php. I was hoping to use the HTML Helper's $html->image() and $html->link() methods to facilitate this, but they're not available in bootstrap.php and I'm not sure how to load/access the HTML Helper where I've defined my function.
Questions:
1) Is this a reasonable/idiomatic place to define a function of this sort?
2) If this isn't the correct place to define the function, where should I define it?
3) If this is the correct place to define the function, how can I go about loading various CakePHP helpers?
Again, I am new to CakePHP, so please let me know if my question is unclear, and forgive my ignorance. I've read/searched through a fair amount of the CakePHP documentation and while I can find plenty of references to loading helpers within Controllers via App::import(...); or $helpers = array(...);, I do not seem to have access to the App object and the $helpers member is specific to the AppController class, I assume. I assume I'm going about this incorrectly, so please help me understand the Cake way of accomplishing this.
No, that is not the correct place for such a function (or more accurately, it goes against the MVC paradigm). A better approach would be to create your own helper for the function. Depending on the complexity of the links you could also use elements.
As a rule of thumb only functions that are completely independent of anything else in the app should be in bootstrap.php, and even most of those would often be better somewhere else.

Preferred way of creating links with backbone.js

I'm trying to wrap my head around backbone.js but I'm finding it hard due to the lack of (IMO) good examples.
First of all, what is the best way of getting a link to an object.
If I want to get the edit url of an Album model I could do album.url() + '/edit', is this really the best way?
Also, I'm trying to make my application work 100% without javascript so I don't want my URLs/links to say /albums/#1/edit, I want it to be /albums/1/edit and override this in JS.
I'm thinking I create normal URLs and use jQuery.live to call router.navigate in backbone.js
I never got this to work however, when I call router.navigate('/albums/2', true) the URL changes but my show action is never called. If I refresh it's called so the route is matched.
What am I missing?
The basic answer, which is kind of frustrating, is "there is no preferred way!". Backbone.js doesn't tell you how to set up links, you can do it any way you like. I found this flexibility just as annoying as you do, at least at first.
So here's the way I'm approaching this on my current project, with the (big) caveat that this is just one of many ways to do things in Backbone:
For the most part, I don't use actual links. There's no explicit reason not to, but it means you have to keep track of a bunch of URL strings that have to be consistent. I would rather stick all the URL formatting in my routers and not deal with it elsewhere.
To open a new "top-level" view, like an editing screen, I set something that fires an event. In the application I'm currently working on, I have a global State model, and to open a new view I call state.set({ topview: MyTopView }). This causes the state object to trigger change:topview.
Any piece of the UI that needs to change when the top-level view changes has an update method bound to change:topview. When the event fires, they look at state.get('topview') and update as necessary.
I treat my routers as only marginally specialized parts of the UI - they're essentially views that render in the browser address bar, rather than the window. Like other views, they update the state object on UI events (i.e. a new URL), and like other views, they listen to the state object for changes that cause them to update. The logic that the editing screen has the URL albums/<albumid>/edit is fully encapsulated in the router, and I don't refer to it anywhere else.
This works well for me, but it adds an entirely new pattern, the global State object, to the Backbone structure, so I can hardly call this the "preferred" approach.
Update: Also note that .url(), in the Backbone idiom, refers to the model's URL in the back-end API, not the front-end URL (it's not like Django's get_absolute_url). There is no method in the default Backbone setup that gives you a user-facing URL for your model - you'd have to write this yourself.
Also, I'm trying to make my application work 100% without javascript; so I don't want my URLs/links to say /albums/#1/edit, I want it to be /albums/1/edit and override this in JS.
you can do exactly this w/ pushState. just enable it in your Backbone.history.start call:
Backbone.history.start({pushState: true})
this tells Backbone to use the HTML5 History API (a.k.a. "PushState"), which uses full URLs exactly like you're wanting.
read up on the history api here: http://diveintohtml5.ep.io/history.html
and I wrote up a 2 part series on using pushstate w/ the second part focusing on progressive enhancement in backbone, to do what you're needing:
http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-1-introducing-pushstate/
and
http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-2-progressive-enhancement-with-backbone-js/
hope that helps :)

Resources