I am having a performance issue with backbone template.
The situation is I have collection of model, each model have a field called 'isSelected'.
I need to render this collection with a template for each individual model. The 'isSelected' field is used for setting the checkbox in the template.
For the sake of discussion, the template is as following.
<div class='thumbnail'>
<input class='checkbox' type='checkbox' {[ if (isSelected) { ]} checked='checked'{[ } ]}
</div>
When I need to make the checkbox all selected, I will update the field to true for each model in the collection.
The code I used is
this.collection.each(function(e) {
e.set("isSelected", true);
});
However, this way is very slow, for a collection contains 25 items, it will take almost 10 sec to make all checkbox 'checked'.
I am expecting that it should least than 1 sec, if i use plain jquery.
Is there any problems with this approach? what's the best approach for this kind problem?
Why don't you set isSelected to true as default in the model? That way you don't have to loop through the collection to set each of them to true.
It's hard to tell what's taking up all the processing time with the amount of code you posted. My first guess would be the render function is being called multiple times. Creating and destroying templates kills performance. If you hard more code posted it might be easy to spot any problem areas.
You should render all of the HTML nodes that could possibility be need. After they are rendered save a jquery selector and use that to toggle the selected.
Most of the time it isn't JS or Backbone that is the bottleneck. It's that JavaScript is triggering the DOM, CSS or reflows constituently and the browser is doing way too much work.
I'm building a PerfView for for backbone. It can render a collection with 1,000,000 models and scroll at 120FPS on chrome. The code is on Github at: https://github.com/puppybits/BackboneJS-PerfView. There's a lot of optimizations in there and comments in the code. One of the techniques in there is sure to solve your issue.
Related
I am a beginner in MVC. In my application, I list categories (as a button) on the left hand-side (inside a div). Just right to this div, there is another div which displays the items associated with the clicked category.
When a category button is clicked, I am planning to call the action of the controller that will retrieve the Items from the database and add these Items to the ViewModel (e.g., model.Items = db.Items...), and then call the View with the updated Model and display the Items.
However, I am curios if it is better to make an Ajax call here and use a partial view for displaying the Items of the clicked category.
If feel like between these two approaches in my scenario only difference will be the page-refresh, they should work the same in terms of speed since both of them require the same database call.
Can anyone share good practices in MVC for such scenarios?
Yes AJAX is faster and good way to update detail in same page without refresh.
For that you have to create JsonResult method in controller. It will give you result in Json.
Try JQuery Template plugin for repeated code.
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
{{each $data}}
<td>${Col}</td>
{{/each}}
</tr>
</script>
<table id="containerTable">
</table>
AJAX Call
$.ajax({
url: 'Your JsonResult Method URL',
type: "GET",
data: data,
beforeSend: function () {
},
success: function (data) {
// It will pass data to template and template will bind parsing json
$('#trTemplate').tmpl(data).appendTo('#containerTable');
//Business logic
},
complete: function () {
// Your Code
}
});
Your JsonResult Method
[HttpPost]
public JsonResult GetData(ViewModel model)
{
// Your Code here
}
using ajax or not when displaying new records in asp.net mvc
Using jquery would be the best approach for this scenario. As you don't have to load the layout page which will have to render the scripts and stuff all over again. Stick on to Ajax calls in MVC as much as possible, The technologies are being improved and a lot of single page applications are out there, And if we still use a page load for every new request then there is no point.
Coming to comparison between passing back Partial View And Json Data. Which is better to use in the application design?
Both partial Views and Json data hold the same weight depending on the scenario.
When to use partial view: Lets say you have a Model and you have to build the view HTML by lot of if checks and loops and possibly some c# code ( in rare scenarios), etc, in such scenario using Partial view would be the better choice, Because if we try to build the same thing in Jquery using json data the complexity of the code required would be high compared to what can be done in Partial views, But still achieving it is possible but wont be that easy and we might make errors during development.
When to use Json Data: If the requirement is like updating a grid, generating dynamic drop down or dealing with some Jquery plugins in the page I think Json data would be better, as many plugins play with json data as the core requirement.
A Small Example Of Deciding Between Partial View And Json Data - interested folks and read through
Lets take a scenario where we have to display a grid of data. This is our initial requirement. So we can happily build our viewModel with data and pass it to our partial view and render the table using for loops. All set, Now the requirement changes and we are asked to build sorting, filtering and paging stuff in our table. So at present we look for a plugin that can be easily integrated with current code and yes the easy one to use at this scenario is Datatables. Ok, we wrote a small Jquery to apply the plugin to the table and all set we have the fancy stuff ready.
Now here is the tricky part, we are asked to add functionalities like add, edit, delete record from the table. Yes its possible but is little tricky to get it done in the best possible way with the current code which we have. What we tend to do is, when ever there is a change in the table we plan to recall the partial view. Which works fine but still asking to ourselves just to delete one record from the table is it good to reload the partial view again?? Definitely NOT,
What can we do? When ever there is any add, edit, delete operation we hit the controller to update the database and we can make the controller return a JSON data and just pass this Json data to the plugin API and refresh the table, This will be more neat and faster. So here you see JSON data would be the better choice. Also some might even want to make it more cleaner by just playing with that one record of data and writing up some jquery code to manipulate the table, which is absolutely fine, But it requires us to pass the Json data itself back from controller.
So having this done, we can go back and refactor our code to make partial view to use json data for the grid initially too or leave it as it is saying the initial load will be a partial view, but following operations would be a json result, which is fine but I feel let all the data related stuff come from one point.
So that explains how a simple module can change from being a partial view to then use Json data. There are scenarios where the story is the other way around, You have to pick the right one for the right work.
I am wanting to customise the edit form in jqGrid so that instead of using the table structured layout provided I would like to use my own custom css structured layout for the form elements. How should I go about modifying the edit form to allow me to use my own custom look?
You can definitely achieve this by jquery ui dialog. However I can not put full code for you but helps you in the steps you have to do.
1 design your custom form whatever CSS and style you want to apply.
Suppose this is youe custome form
<div id="dialog-div">
<input type="text">
</div>
2 on jquery dialog open the dialog on your jqgrid editbutton click
$("#edit").click(function(){
var rowdata = $("#coolGrid").jqGrid('getGridParam','selrow');
if(rowdata){
$("#dialog-div").dialog('open');
var data = $("#coolGrid").jqGrid('getRowData',rowdata);
alert(data);
}
});
by default it will close as-
$("#dialog-div").dialog({
autoOpen: false,
});
Now as you get data in variable you can put in your edit form and of jquery dialog button save it according to your logic.
Hope this helps you.
I would recommend you first of all to read (or at least look thorough) the code of form editing module which implement the part which you want to replace. You will see that it consist from more as 2000 lines of code. If you write "I would like to ..." you should understand the amount of work for implementing what you ask. If you are able to understand the code and if you are able to write your modification of the code even using libraries like jQuery UI then you can decide whether it's worth to invest your time to do the work. The main advantage of using existing solutions is saving of the time. What you get in the way is not perfect, but using existing products you could create your own solutions quickly and with acceptable quality. The way to study existing products which you can use for free seems me more effective as large investments in reinventing the wheel.
http://guriddo.net/?kbe_knowledgebase=using-templates-in-form-editing
Using templates in form editing
As of version 4.8 we support templates in the form editing. This allow to customize the edit form in a way the developer want. To use a template it is needed to set the parameter template in the edit add/or add options of navigator. This can be done in navigator or in the editing method editGridRow :
$("#grid").jqGrid("navGrid",
{add:true, edit:true,...},
{template: "template string for edit",...}
{template: "template string for add",...},
...
);
and in editGridRow method:
$("#grid").jqGrid("editGridRow",
rowid,
{template: "template string",...}
);
To place the CustomerID field in the template the following code string should be inserted in the template string
{CustomerID}
With other words this is the name from colModel put in { }
The usual problem with table layouts is when you have columns with different widths, especially with those very wide.
I solved my problem adding the attr colspan to wide columns in the beforeShowForm event.
for example
"beforeShowForm":function() {
$('#tr_fieldnameasinColModel > td.DataTD').attr('colspan',5);
}
It's not fancy but it worked for me. Perhaps there is a more elegant way to do the same.
I could arrange the fields in several columns without having to make the form extrawide.
When user click on edit button the page navigate to another page, based on Id get the details of a row and you can display the values..
Previous answer of Creating a link in JQGrid solves your problem.
To avoid calling applyBindings multiple times on the same DOM element, I wrap my various viewmodels in an observable. then just change that observable to whatever view model i wanna see and BAM...that works.
until i do something like this:
<div data-bind="if:$data">
...some bindings in here
</div>
when i change view models, the bindings inside any "if:$data" blocks do not update.
here's a fiddle to really demonstrate this: http://jsfiddle.net/btrauma8/2TxME/
This would have worked properly prior to KO 2.2. In 2.2, we made if and ifnot more efficient by only re-rendering the section when the value actually changes between truthy/falsy.
There were many cases where people would bind against something like if: items().length and the entire section would be re-rendered everytime that an item was added.
In your case, you can overcome this pretty easily by just using the with binding instead of if. Since, you are binding against $data, it will not actually change the context and will give you the result that you are after.
I managed to get jquery datatables plugin to work with asp.net mvc 3 so it posts back json, and with a search function.
Problem now I that I need to move the search box and add a "language" filter outside it's "normal" position next to a custom made menu.
Is there a way that I can integrate:
Language: <select name="languageid">
<option value="SV">Swedish</option>
<option value="EN">English</option>
</select>
Keywords: <input type="text" name="keywords">
To refresh datatables when languageid or keywords change? and still have sorting, paging working?
My brain is only firing at half power today, but the short answer is that this can be done; it's just my suggestions that are kind of vague...sorry!
There are a whole set of language options in oLanguage; it was a bit "Too Long, Didn't Read" for me to sort through, but perhaps something there will help you identify where to set up a language switcher
You can remove the search box from the main table and set up your own, using the fnFilter method to trigger the search
Depending on how your other options are configured (server-side, for example), there are methods to trigger a refresh of the table. You would bind a listener for the languageid or keyword change action (.on('change', '#languageid', function(e) { /* ... */ })) which would fire the appropriate refresh action (in my instance which uses server-side, I use fnDraw())
I'm sorry about the directionless advice, but I wanted you to know at least that this is possible. Posting the question on the datatables.net forums directly might get you the best possible answer.
I have a partial view that I have included on my _Layout.cshtml. It simply has a javascript function that changes an image based on the state of my system. I don't need to reload any data, I don't need to go to the code of the controller for anything, I simply need to reload that partial view.
I tried many of the examples that I found here but couldn't get any of them to work. I felt as if they were too complex for what I was doing anyway. Any guidance would be appreciated.
Thanks,
Steve
If the partial is loaded into the layout directly then there's no straightforward way to refresh it, because it's basically a part of the complete rendered page.
Your best bet is to render the partial using $.load or whatever equivalent you have available by hitting a controller method and rendering the result into a container (like a div). You would have to do this within a script that is loaded with the layout itself, by observing document.ready or something like that. Once you have that in place then it's trivial to keep reloading or refreshing the contents by hitting the controller method as many times as you need. For example in jQuery:
$(document).ready(function () {
RefreshPartial();
window.setInterval(RefreshPartial, 10000);
});
function RefreshPartial() {
$('#container').load('/some/controller/endpoint', {parameters});
}
This will call the controller method, and set the inner contents of the element identified with #container. You can call RefreshPartial as many times as you want.
Partial views only exist on the server. The only way to "refresh" the partial is to go back to the server to get it again.
Obviously, you must be doing something in the partial that needs refreshing. Whatever that is, should be callable from javascript to do the refresh.