How to format the values of a model in Marionette Backbone View before rendering? - view

If you implement the onBeforeRender method the is no way to access the model values in order to format them temporarily
Ideally you would want to format the values just before rendering without changing the model values of course!
How to do it?

By checking this link: http://derickbailey.github.io/backbone.marionette/docs/backbone.marionette.html
You will find that serializeData is being used just before rendering the template
So by overriding it, like below you can format the object values any way you want before rendering
serializeData():any {
var obj = super.serializeData();
obj.totalEnergy = Math.round(obj.totalEnergy).toFixed(0)
return obj
}

Marionette Views also have templateHelpers for this purpose. templateHelpers can be used to provide any additional data to the view apart from model. Functions can be specified to format model's data to be rendered on the view. Check out the basic example for template helpers in Marionette view's docs - http://marionettejs.com/docs/marionette.view.html#basic-example

Related

How to make a laravel 5 view composer

I'm still learning Laravel and I'm working on a small project to help me understand better. In the project, I am in need of a global array, so that I may display it or its attributes on every view rendered. sort of on a notification bar, so that each page the user visits, he/she can see the number of notifications (which have been fetched in the background and are stored in the array).
I have done some research, and realized that I have to fetch and compile the array in a view composer I think. But everywhere I go, I cant seem to understand how to make a view composer.
I need to fetch the relevant rows from the database table, and make the resulting array available to each view rendered (I'm thinking attaching it somehow to my layouts/default.blade.php file.). Please help, any and all advice is greatly appreciated:)
You can now inject services on your view
More info here: https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/2
You have to use Sub-Views of laravel blade. I guess your functionality is like a sidebar or like a top bar which will be rendered at every page.
//Your Controller pass data
class YOUR_CONTROLLER extends Controller {
public function index()
{
$data = YOUR_DATA;
return view('YOUR_VIEW_FILE', get_defined_vars());
}
}
//In Your View File
#extends('LAYOUTS_FILE')
#section('YOUR_SECTION')
#include('YOUR_SUB_VIEW_FOR_NOTIFICATION')//You need not pass any data passed all data will be available to this sub view.
#endsection
In your sub view
//Do what ever you want looping logic rendering HTML etc.
//In your layout file just yield or render the section that's it
#yield('YOUR_SECTION')
More explanation can be found Including Sub-Views

EmberJS: programmatically adding a child view to a collection view without changing underlying content

My EmberJS app is confusing me a lot at the moment. I have a collection view, that in turn defines an itemViewClass of a custom view I have defined in my code. Something like:
App.CarouselView = Ember.CollectionView.extend({
itemViewClass: App.SlideView.extend(),
});
And this CarouselView is rendered inside a template that has a dynamic segment backing it (I hope this makes sense?) . The controller for these dynamic segment is an array controller because the model for these dynamic segments is a collection :) (more confusion, please let me know)
App.SlidesController = Ember.ArrayController.extend();
By now all of you have figured that I am basically rendering a bunch of slides inside of a carousel. And these are dynamically backed in the collectionView by setting the property
contentBinding:'controller' // property set in CarouselView, controller corresponds to SlidesController
The confusion begins now. I want to add a slide to the existing set of slides. So I provide a button with an action : 'add' target='view'
In the SlidesView,
actions:{
add: function(){
var carouselView = this.get('childViews')[0];
// SlidesView has carouselView and another view as it's child, hence this.get('childViews')[0] is carouselView
var newCard = carouselView.createChildView(App.SlideView.extend());
carouselView.get('childViews').pushObject(newCard);
}
}
The above piece of code sucks and hurts me bad. I want to basically add a new SlideView to my CarouselView collection programmatically upon a button trigger. But apparently Ember recommends that childViews should not be manipulated directly and I ought to instead change the underlying content.
It states in my console.log that manipulating childViews is deprecated etc.
So essentially I need to add something to my content to my SlidesController content ? However, I don't want to add something to the content, this is just a soft add, that is providing the user with a slide so that he may choose to edit or add something if he wants to. He can always discard it. A hard add that will require me to persist the new slide to the DB will come once the user decides to save this information.

Knockout JS, MVC 3 and View Model Server Side Data as JSON

So I have a problem...I am separating concerns in my web app: HTML in razor pages and JS in js files. My problem lies in the fact that I want to use data from my controller passed down in the view model from the server as the options of a select list. The problem lies in the fact that I have separated my js from my HTML and I can't access Razor inside the js files.
I have a list of items coming down into my view model...
public List Stuffs { get; set; }
I json encode it server side and make sure to take care of circular refrences, so it looks like this
[{"id":1,"name":"blah"},{"id":2,"name":"blah2"},{"id":3,"name":"blah3"},{"id":4,"name":"blah4"}]
The problem is, I want to keep my separation of concerns, so how do I get that array into my js file so I can bind it to a select list using knockout? I definitely don't want to do another round trip to the server.
So lets say you have some view that looks like this:
<div> (Some stuff) </div>
<script type="text/javascript">
var initialData = //Your JSON
<script>
And then in your javascript (which you have linked below your view, so that it loads after it), you have something like this:
var data = initialData || {} //Or some other default value, in case initialData wasn't set
This will load in the initialData if it was set, or use nothing (or a default your define) if it wasn't. Loosely coupled.
Of course, more complex data will require you to standardize the strucure, but this is essentially one method that allows you to pull in data from the razor generated View without tightly coupling it to your javascript file.
Does your Javascript file contain a view model in the form of an instantiable function, e.g. something like:
function MasterVM(data)
or an object literal, e.g.
var masterVM = { ...
? I tend to go for instantiable view models (partly because they chain down through a hierarchy of view models using the mapping plugin - the top level one builds its children) and that being the case I think it's nice for the Razor view to instantiate the view model with the JSON rendered from the MVC view model, e.g.:
var masterVM = new MasterVM(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Or even have the Knockout view model "owned" by a revealing module and initialise it like:
productModule.init(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Then productModule is also responsible for other things like mediating between your view model(s) and the server, watching for dirty state, etc.
Also, doing another round trip to the server is not necessarily bad if you are sourcing a massive set of reusable options which you'd like the browser to cache. If you are, you might want to have an MVC controller which emits a big object literal containing all of your commonly used options, which you can then use as the "options" property across multiple selects. But if your options are specific to the particular view model, then I guess they have to be part of your view model.

Ember.js: How can I decouple my views from my controllers?

I'm trying to restructure tightly coupled portions of an ember.js app, particularly views and templates to controllers.
All the examples I've seen bind views directly to controllers in the view's class definition, or by pass the (global) controller path to the view in the template itself.
The TargetActionSupport mixin (DelegateSupport in sproutcore, I think) seems like a good candidate, but would still require the target (controller) and action to be set in the template itself.
Ideally, I would like to instantiate my views in my controller (somehow), set targets and actions, but also set presentational variables in my templates (ex: static classes, id), but I'm not sure how to accomplish something this, or whether it's the right approach.
You can programmatically instantiate views and insert them into the DOM wherever you'd like:
var view = Ember.View.create();
view.appendTo('#someElement');
If you want to eliminate global binding paths, you can pass in a controller reference to the view on instantiation:
var controller = Ember.Object.create({content: {}}),
view = Ember.View.create({
controller: controller,
contentBinding: 'controller.content'
});
I'd also suggest looking into the Ember StateManager.

Custom MVC Framework: How do I propogate data to a view?

I am creating a custom MVC framework.
I verrrrry loosely modeled it after the codeIgniter framework, but it's ground-up custom for the most part.
I'm at the point where I have URL's routing to the appropriate controller actions, but I'm stuck at the point where I generate a view that can utilize data generated by the controller.
I have views defined (static HTML with inline php ready to populate dynamic data), and I have the destructor of my base controller require()'ing the view in order to populate the browser with the view... here's the code:
public function __destruct()
{
if ($this->bSuppressView === false)
{
require(APP_PATH.'views/layout/header.php');
require(APP_PATH.'views/'.$this->sController.'/view.'.$this->sController.'.'.$this->sAction.'.php');
require(APP_PATH.'views/layout/footer.php');
}
}
Basically, when the controller is done executing, the teardown process of the base controller will then include the global header view, the controller's action's view, and then the global footer view, which should populate the webpage with everything for the URL that was requested...
HOWEVER, I cannot access any globally defined variables from the embedded php in the view code. In my bootstrap class, I define a bunch of local variables such as my config variable, etc., but the view seems to consider those variables undefined. Additionally, i'm unsure how to allow the view to access data that the controller may have generated. Where do I "stick" it to make it available to the view?
Let me know if this isn't clear, and i'll update.
Thanks!
UPDATE: I've discovered that while doing it this way, the "environment" of the views is within the controller object, which, as far as I can tell is a great thing! I don't have to propogate anything anywhere but in the controller, and I can use "$this->" in the views to get access to anything public or private from within the controller class!!!
That leaves the question: is this "normally" how it's done in MVC? What's the BEST way to propogate a view? I think this will suit my purposes, and I will post back if I discover a limitation to just treating the embedded view php as "within the scope of the calling controller"...
The way this is generally done, is that the view is actually an object. You pass that object you're variables, and that view object takes the template you gave it, includes it so that it's in the current scope, and grab the output into a variable using output buffering.
To give you a basic idea:
// controller object
$this->set('key','val');
$this->render('mytemplate');
// controller base class
$view = new View;
$view->setData($this->getData());
// view class
class View {
....
function render() {
ob_start();
include $this->resolveTemplate();
$out = ob_get_contents();
ob_end_clean();
return $out;
}

Resources