Navigate to viewModel and pass Model value - json

I am getting the data from server in JSON and I am converting that to my viewModal. Now I am loading the a new view using return router.navigate('results'). But at the same time I want to pass the viewModel which I created from the JSON object to be passed to this view. By default the "results" viewModel is getting called but it is having blank values.
A small code snippet will be helpful as I am new to Durandal JS.

The best answer I have is to store that information in a separate module, like so:
storage.js
define(function(require) { return []; });
viewmodel.js
define(['storage'], function(storage) {
$.get('uri', function(data) {
data.forEach(function(obj) {
storage.push(obj);
});
});
});
This is not the most elegant solution. I'm really interested if there is a clean way to pass data from and to separate view models on activation, but so far I have found none.

Ended up finally something like this.
In the module where I want to navigate, I created an "Initialize" function which accepts a JSON object. Using this JSON object I initialized all properties in the viewModel.
From the page from where I have to navigate there I did a "require" on the module where I want to navigate next. Then I called the "Initialize" method and passed my JSON object.
After this I used router.navigate method to go that module.
This way when I navigated, I got all the values which I wanted to pass from one view to other. Hope this approach will help someone else.

The answer from Matthew is certainly similar to the way that I currently do it, once the data is held within your separate module (i have a path called modules/data/someDataStorage) you can use either events or a knockout observable to make the data update through to your view models.
In your case I would make updates to your shared module to store information on your request and then on the activation of your results module, go and get the data from that shared module.

Related

JSON serialisers and alternative http responses with Django

I'm trying to create a filter system on a click event - using an AJAX post method to update the context that is shown on the template.
I'm currently using:
return HttpResponse(json.dumps(context), content_type="application/json")
To return a response with a context object. However, this doesn't quite work with certain object types:
TypeError: is not JSON serializable
I know there's something regarding serialisers but I'm currently unable to either a.) use them correctly or b.) use them at all.
For some context I'm passing filter variables to the view with the AJAX post method - then:
posts = Post.published.filter(category__name__in=category_filter_items)
And adding this to my context:
context['posts'] = posts
Would anyone know the correct way to update the context is such a manner?
First of all, you should know that once the Django template is rendered, you can't dynamically modify its context without rendering it again. See template documentation.
Before modifying dynamically your template, you should really consider a way to filter your data by calling a view that renders the template again with the context you need.
Option 1: Render the template again
def my_view(request):
posts = Posts.objects.all()
# TODO: Filter the posts against the request
template = loader.get_template('template.html')
context = {
'posts': posts,
}
return HttpResponse(template.render(context, request))
Option 2: Modify your template dynamically
If you're sure that modifying your template dynamically is your best / only choice, you've got different ways to achieve this.
One of them is changing your template via jQuery, loading a subtemplate that is rendered by your filtering view. Take a look at this issue.
Another way is to get your filtered data via a JSON Api and make sure your template is updated accordingly. You may want to use Angular for instance, which uses a MVVM architecture pattern.
How to serialize models in Django?
Django provides serialization of models as a core feature.
Serializing your models to JSON is as simple as:
from django.core.serializers import serialize
serialize('json', SomeModel.objects.all())
If you need to implement an API with serialization of models AND filtering, you may want to use django-rest-framework.
What about use JsonResponse instead of HttpResponse? also you need to define a serializer for Post model.

Pass Json Object from Play! framework to HighCharts JS

http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.

Laravel return json or view

I'm developing an API where if the user specifies the action with .json as a suffix (e.g. admin/users.json), they get the response in the return of json, otherwise they get a regular html View.
Some actions may not have a json response, in which case they would just return a html View.
Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.
I suggest you to create your application as an api.
Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).
The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.
This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.
More information:
Consuming my own Laravel API
Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.
In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().
public function controllerMethod(Request $request)
{
if ($request->ajax() || $request->isJson()) {
//Get data from your Model or whatever
return $data;
} else {
return view('myView.index');
}
}

zf2 json view script

We are currently trying to set up routes in such a way that the returned content-type can be set using a route parameter. The routing is all working properly now, but there is one problem. If one requests html, then the normal view script is rendered. The data we provide to this script can be anything from a string to a collection of objects, and the view script decides what to show to the user.
If however JSON response is requested, then we just provide the data returned from our controller as JSON. However, some data should not be made publicly available to the user, and hence some filtering is required. Is there any possibility to use JSON view scripts (as in ZF1 with context-switch) in order to support such filtering? Or maybe another method?
There is no such thing as a JSON script which lets you decide what to render and what not. You have to provide the proper data in the view model such that only the data is given that is eligible to be displayed.
I have been thinking about a hook in the JSON renderer so you can filter the view model's data based on the context of the request, but such thing does not exist yet. Unfortunately, you have to select the data in your controller or model.

How to specify JSON url to js method in a JSF based application

I am implementing a multiselect autocomplete textbox (similar to one that Stackoverflow uses for tags input), using fcbkComplete. For implementation, I need to transfer JSON objects to a Jquery function from JSF. (There's a need to specify JSON url as parameter to fcbkComplete).
$("select0").fcbkcomplete({
json_url: "fetched.txt"
});
I am using JSF 2.0 with Primefaces 3.0M3. I would appreciate if someone can show me a direction as to how I can specify a JSON url to a js method in a JSF based application.
Thanks
At its simplest, you can just let a JSF managed bean getter return the desired JSON as a String and assign it to a JS variable which is inlined in the view template:
<script>
var json = #{bean.json};
// ...
</script>
(note that the variable value is unquoted! i.e. using var json = '#{bean.json}'; won't work out)
You can if necessary use among others Google Gson to easily convert between Java objects and JSON strings. You can if necessary put that <script> inside a <h:panelGroup> with an id so that it can be re-rendered upon an ajax request. You can if necessary end up wrapping this in a composite component.
True, it's very spartan, PrimeFaces may have better ways for approaching this, but I'm not aware of any.
As a completely different alternative, when the data does not depend on anything in the JSF context (expect of maybe some session scoped managed bean, which is available as a HttpSession attribute anyway), you can also create a simple servlet which does the job upon a jQuery.ajax() call. You can find several examples in this answer: How to use Servlets and Ajax?