serializeData vs. templateHelpers? - backbone.js

In Marionette, afaik these two snippets achieve the same purpose:
serializeData: function() {
data = super;
data.foo = "bar";
return data;
}
and
templateHelpers: function() {
return {
foo: "bar"
}
}
What would be the difference and when to use one or the other?

In your example I can't think of any practical difference.
Semantically, though, I think that serializeData() is the better fit when you're transforming the existing model data into something else. It's more complicated to use, because you have to think about the default serialization of the model, which could include a custom model.toJSON() call. For example, your model might override toJSON to avoid sending some unneeded data to the server, but if you need that data in the view you will want to add it back with serializaData().
templateHelpers, on the other hand, is more straightforward, since all it does is add new attributes. It makes sense when there's some computed data you want to have available in the template that isn't part of your model.
In the example you cite above, I would use templateHelpers, because it's a better fit semantically and because it's simpler.

Related

Why aren't function reference in JSX "sugar"ified?

For Example,
We could just use
onClick={(foo)}
or something else.. instead of
onClick={this.foo.bind(this)}
Just curious if there is any particular technical constraint.
Let me answer the question from a design/philosophical perspective, instead of a technical one (the other answers do that pretty well already).
React COULD have, there would be no problem to that. But why have multiple ways to do things when you can have one (React tries to stay as close to ES standards as possible). If there are multiple ways to do a single task, it'll affect readability across codebases, making it harder for developers to ease into a codebase since they would have to unravel layers upon layers of abstraction till they gets to the core idea.
Basically, I think it was a design choice to NOT add a lot of the syntactic sugar that could have been added (JSX itself is already a form of syntactic sugar, we don't need syntactic sugar on our syntactic sugar).
From the React Docs:
"In general we resist adding features that can be implemented in userland. We don't want to bloat your apps with useless library code. However, there are exceptions to this."
"We prefer boring code to clever code. Code is disposable and often changes. So it is important that it doesn't introduce new internal abstractions unless absolutely necessary."
Source: https://facebook.github.io/react/contributing/design-principles.html
Representing the ideas from this talk: https://www.youtube.com/watch?v=4anAwXYqLG8
onClick={foo} is something completely different to onClick={this.foo.bind(this)}, and parentheses are required for maths.
.bind causes a new function to be created on every single invocation, so this would not be very performant.
(I assume) an aim of JSX to try and be as close to regular JS as possible so it's easy to pick up.
It is not the realm of JSX to add new language elements; a bind operator is most definitely a new language element.
If you notice, JSX doesn't provide any new language constructs other than what is necessary to call React.createElement. Additionally, you probably wouldn't want to use .bind like this anyway due to fact it's creating a new function every time. Finally, the parens are required for mathematical operations - you couldn't use {()} because what if I wanted to use a mathematical operation like {(a + b) * c}? Any interpolation that JSX does must be a JavaScript expression, currently, so unless JavaScript itself supports this syntax it's unlikely the interpolation will too.
You may be interested in the function bind operator, but I'd recommend you avoid using bind in this manner; instead, bind the functions once in the component constructor, like so:
class MyComponent extends Component {
constructor() {
this.boundOnClick = this.onClick.bind(this)
}
render() {
return <button onClick={this.boundOnClick}>Foo</button>
}
}
// with function bind operator
class MyComponent extends Component {
constructor() {
this.boundOnClick = ::this.onClick
}
render() {
return <button onClick={this.boundOnClick}>Foo</button>
}
}
This ensures you only create the bound function once. For stateless components, you don't have access to this anyway so there's no need to use bind.
If JSX were to introduce an alternative syntax to this, I personally would be opposed to it, though if they could overcome the limitations I've mentioned above, there's nothing technically stopping them.
It is more a problem with ES6 which does not have automatic binding of "this" to class methods. In ES7, there is a proposal to introduce a new operator ::. With ES7, you could write:
onClick={this::foo}

Are there any objective reasons why it is better to not call functions in Angularjs Views to display data?

To make a long story short, in our application at work, we have a function that creates multiple objects that inherit methods from a prototype.
As such:
function MileCounter(totalMilesRan, numOfDaysToRunThem) {
this.totalMilesRan = totalMilesRan;
this.numOfDaysToRunThem = numOfDaysToRunThem;
};
MileCounter.prototype.avgMilesPerDay = function() {
return (this.totalMilesRan/this.numOfDaysToRunThem);
}
And then in the view, this is called like this:
<div> {{mileObj.avgMilesPerDay()}} </div>
The disagreement comes from their belief that the average should be provided to the mileObj in the controller so the average can be called in the view just as they would to get moneyObj.totalMilesRun as:
<div> {{mileObj.avgMilesPerDay}} </div>
Something to keep in mind is that the actual objects in question have many more properties than just two and the number of objects being created is usually in the dozens but could eventually sky rocket into the hundreds or even thousands.
My Coworkers believe that the view should not be concerned at all with calculating data and should only be concerned with displaying it.
My Question: Is there an objective reason why it would be better to add the avgMilesPerDay value directly to each object, rather than just calling a prototype method to handle it? It is my understanding that adding a bunch of properties to objects could eventually be a drag on memory when there are enough objects being created, with enough properties on each one, and that having simple prototype methods could help ease that burden.
Advantages of calling a function:
less memory usage
more encapsulation: changing the value of totalMilesRan or numOfDaysToRunThem automatically changes the value of the average
Advantages of adding a field for the average:
slightly more efficient: the average doesn't need to be computed again and again
I would keep using the function from the view unless you have a performance problem, and have proven that it comes from the function call, and it can't be solved in another way (like one-time binding for example).

Immutable State - Propagating Changes to the GUI Efficiently

In a previous question I asked how to idiomatically implement an observer pattern for an F# application. My application now uses a MailboxProcessor as reccomended and I've created some helper functions to create sub-MailboxProcessor's etc. However, I'm at a mental block when it comes to specific case scenarios w.r.t. GUI binding.
Lets say I have a model as such:
type Document = {
Contents : seq<DocumentObject>
}
And the GUI (WPF, XAML) requires binding like so:
interface IMainWindowViewModel
{
IEnumerable<Control> ContentViews { get; }
}
Each ViewModel for each Control will require a DocumentObject (its underlying model) and a way of knowing if it has changed. I supply this as a sub-MailboxProcessor<DocumentObject> so that changes may be propagated correctly, I'm moderately confident this pattern works. Essentially, it maps the service outputs and wraps modification requests (outer interface example below):
let subSvc = generateSubSvc svc (fun doc -> doc.Contents[0]) (fun f -> fun oldDoc -> { oldDoc with Contents[0] = f Contents[0] })
let viewModel = new SomeDocObjViewModel(docObjSvc)
new DocObjView(viewModel)
Now, imagine a modification command now deletes a DocumentObject from MyDocument. The top-level MailboxProcessor now echoes the change to IMainWindowViewModel using it's IEvent<MyDocument>. And here's where my problems begin.
My IMainWindowViewModel doesn't really know which DocumentObject has been deleted. Only that there's a new Document and it has to deal with it. There may be ways of it figuring out but it never really knows directly. This can force me down the path of having to either re-create all the Control's for all DocumentObject's to be safe (inefficient). There are additional problems (such as dangling subSvc's) which I also haven't mentioned here for brevity.
Normally, these kind of dynamic changes would be dealt with something like an ObservableCollection<DocumentObject> which is then mapped into an ObservableCollection<Control>. This comes with all the caveats of shared mutable state and is a little 'hackish'; however, it does do the job.
Ideally, I'd like a 'pure' model, free from the trappings of PropertyChanged and ObservableCollections, what kind of patterns in F# would satisfy this need? Where is it appropriate to draw the line between idiomatic and realistic?
Have you considered using the Reactive Extensions (and Reactive UI further down the road) for the purpose of modelling mutable state (read: your model properties over time) in a functional way?
I don't see anything wrong technically to use an ObservableCollection in your model. After all, you need to track collection changes. You could do it on your own, but it looks like you can save yourself a lot of trouble reinventing the observable collection, unless you have a very specific reason to avoid the ObservableCollection class.
Also, using MailboxProcessor seems a bit overkill, since you could just use a Subject (from Rx) to publish and expose it as an IObservable to subscribe to 'messages':
type TheModel() =
let charactersCountSubject = new Subject()
let downloadDocument (* ... *) = async {
let! text = // ...
charactersCountSubject.OnNext(text.Length)
}
member val CharactersCount = charactersCountSubject.AsObservable() with get
type TheViewModel(model : TheModel) =
// ...
member val IsTooManyCharacters = model.CharactersCount.Select((>) 42)
Of course since we're talking about WPF, the view-model should implement INPC. There are different approaches, but whichever one you take, the ReactiveUI has a lot of convenient tools.
For example the CreateDerivedCollection extension method that solves one of the problems you've mentioned:
documents.CreateDerivedCollection(fun x -> (* ... map Document to Control ... *))
This will take your documents observable collection, and make another observable collection out of it (actually a ReactiveCollection) that will have documents mapped to controls.

CakePHP: Use Inflector Class over whole array

I need to use Inflector::slug() over all results fetched from my database, which are, of course, retrieved in an array. Is it possible somehow, or I'll need to loop each result and slugify it?
Thanks!
PHP's array_map() function might do what you need (although it assumes a simple indexed array).
array_map( 'Inflector::slug', $your_result )
If you're looking at something more complex, CakePHP's Set utility class may be helpful in a multi-step implementation.
I haven't tried this in a CakePHP context (i.e. mapping through a CakePHP class method), but I can't think of any reason it wouldn't work off the top of my head. Maybe it'll at least get you started.
Depending on the array you can use array_walk or array_walk_recursive.
Something like this should work.
This is for 5.3+;
array_walk_recursive($posts, function(&$value) {
$value = Inflector::slug($value);
});
If you wanted to limit it to a certain field you could also do something like this:
array_walk_recursive($posts, function(&$value, $key) {
if ($key == 'title') {
$value = Inflector::slug($value);
}
});
I haven't used Cake in a while but like Rob Wilkerson said, you might find that the Set class could make lighter work of this.

EXTJS - How to verify if element exists?

I need to know if a boxComponent exists in a ext formPanel in order to take some actions... Is there some way to know that?
something like this:
if(getElementById("boxId") != 'undefined' ){
alert('exists');
}
The common pattern that most people use is this:
var myBoxCmp = Ext.getCmp('cmpId');
if(myBoxCmp){
myBoxCmp.doSomething();
}
Same thing for Elements:
var el = Ext.get('elId');
if(el){
el.doSomething();
}
You can also use methods like Container.findById, but if you have an id (assuming it is unique, which it should be) just use getCmp.
EDIT: Several years have passed since this original answer, and nowadays getCmp is generally frowned upon as a code smell and should typically be avoided in applications (promotes global references, which generally indicate poor design when they are required). It's typically better to use controller references (if using MVC) or the various ComponentQuery or Container methods to reference related components (e.g. down, child, getComponent, etc.)
I just do it the extjs way and i prefer not to use getElementById() which is a native js method and may cause incompatibility issues in diffrenet browsers:
if (!Ext.getCmp('componentid')) {
alert('boxId is empty');
}
You can use Ext.get('boxId'). It returns null if the object doesn't exist and returns an Ext.Element object.
Using getElementById would probably be much faster though. Do you have any specific objection against it?
Use the Ext.isEmpty(object) method.
if(Ext.isEmpty(getElementById("boxId")) {
alert('boxId is empty');
}
function openView(cid) {
shortName = cid.substr(cid.lastIndexOf(".")+1, cid.length);
if(Ext.get(shortName) == null) Ext.create(cid);
Ext.Viewport.setActiveItem(Ext.getCmp(shortName));
}
This function opens a view like
openView('MyApp.view.Oeffnungszeiten');
and if the View exists it accesses the old instance

Resources