Can this jQuery dynamic DOM manipulation be done with Vuejs? - javascript

I have a page that makes AJAX requests to update content. I make the request and get JSON back that looks something like this:
{
"item": {
"id": "myElementToChange",
"value": "My Content to update"
}
}
I then parse it and update the page like this:
var str = '{"item": {"id": "myElementToChange","value": "<h1>My Content to update</h1>"}}';
var json = JSON.parse(str);
var $element = $("#"+json.item.id );
$element.html(json.item.value);
Can I do something similar in Vuejs? Or do I have to predefine a template to accommodate each type of IDs that I want to update?
http://jsfiddle.net/ogewwqzt/

I would say first that even if you use Vuejs instead of jQuery, you can still use plain js functions in your vuejs code, such as:
document.getElementById(json.item.id).innerHTML = json.item.value;
Of course it is not taking advantage of the Vuejs functionalities.
The vue way would be to use declarative rendering :
<div id="app">
{{ message1 }}
{{ message2 }}
</div>
var app = new Vue({
el: '#app',
data: {
message1: 'yo',
message2: 'yo2'
}
})
then do your ajax call in a method, update the data (message1 and message2) with the result of your call and let vuejs reactivity features update the DOM.
Also, it seems like a very weird choice to have your server directly send an HTML id. Why would the back-end need to know the name of your html id ? You probably want to be able to change an html id without modifying the server code.

Related

How to pass a string from back end (java) to the front end(typescript) and have it appear on UI?

Simply put, I'm trying to pass a string from my java back end to my typescript front end so that this same string will display in the UI. Neatly below the purple bar like so:
Image
I think in the back end I have to return a string, send it through a controller, and have the front end receive the string from there but I've had limited success doing that so far.
Rather than debug my code, I was wondering if anyone here could point me to a simple tutorial or project that does exactly what I'm trying to do: Take a string from the back end, return it, have it received by the front end, then have that same string displayed on the UI. That way I can just mirror the implementation. I've tried googling for simple examples like that but I've come up empty so far.
As you just want to understand the direction/Suggestion on How to achieve the requirement. Few things you need to consider :
You have to make a decision that you require to use any frontend related frameworks/libraries or you want to do that in pure JavaScript ?
To get the data from Java backend you have to make an AJAX call from the page and simply bind that in UI DOM.
In pure JS, You can bind the string with the help of element ID.
const str = 'This string is coming from API';
document.getElementById('resultDiv').innerHTML = str;
<div id="resultDiv"></div>
If you are going to use any library/framework then there is a way one-way/two-way data binding. I am just showing an example based on Vue.js for the demo purpose.
new Vue({
el: '#app',
data: {
message: null
},
mounted() {
const str = 'This string is coming from API';
this.message = str;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>{{ message }}</p>
</div>

How do I make my global.js file talk to Jade?

I have a global javascript file where I'm reading some data from a database.
//globals.js
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#carInfoReg').text(thisUserObject.reg);
$('#carPhoto').source(thisUserObject.LinkImage);
The content of thisUserObject.LinkImage is a link (properly formatted with "http://") and I want to use that to set the source attribute of an image tag in my jade file.
br
strong Photo
img(src='#{carPhoto}')
however it's not displaying anything at all.
What am I doing wrong? How can I talk to jade with data from my globals.js file?
Once jade is compiled, it has nothing to do with jade anymore. If you just want it to work, vue is the best choice. It's very intuitive.
Jade:
script(src="https://cdn.jsdelivr.net/vue/latest/vue.js")
#app
br
strong Photo
img(src='{{carPhoto}}')
JS:
var vm = new Vue({
el: '#app',
data: {
imgSrc: "http:www.foo.com",
carInfoReg: " This carInfoReg "
}
});
// it is easy to manipulate the data inside vue.
//when you update data of Vue instance, its view will be updated automatically.
vm.imgSrc = "http://www.bar.com/dwagsgd";
JSFiddle

How to add CSS / HTML to a Ajax call

I'm calling my server each time a user enters / deletes a key in a search box, retrieving a large list of lists in JSON, which I loop through through in JS. In order to get the data onto my template I add HTML & CSS using Jquery. Here's an example to show what I mean...
<script type="text/javascript">
$(document).ready(function() {
$('#input-search').keyup(function(data) {
var search = $("#input-search").val();
$.get("/search/", { search:search }, function(search){
var matches = (search.search);
for (match in matches){
console.log(matches[match].full_name);
$(".searchable-container").append("<div>").addClass("items col-xs-12 col-sm-12 col-md-6 col-lg-6").append("<div>").addClass("info-block block-info clearfix").append("<div>").addClass("square-box pull-left").append("<span>").addClass("glyphicon glyphicon-user glyphicon-lg").append("<h5>")
}});
});
});
</script>
I feel like this is not the best way to style my returned data as it's requiring a lot of trial and error, and it looks ugly. For example, using Jinja templates, I can simply add {{ curly braces }} and it calls my data wherever it's needed. I'm just wondering if there is something I'm missing, or a better way to do what I'm doing, given I'm new to JQuery.
I suggest you to don't append directly the object. Just create it and then append it. Something like:
var obj1 = $("<div>");
var obj2 = $("<div>");
obj1.addClass(...);
...
$(".searchable-container").append(obj1);
$(".searchable-container").append(obj2);
But this is the way to go IMO.

can't 'ng-repeat' through javascript array in AngularJS, (by getting a JSON object from Django)

This question is not Django related in any way because my Django view which returns a dummy JSON object works perfectly, just thought I would share the Django view which converts a
Model.objects.all() into pure JSON data then returns this pure data for an Angular controller to read and process through an ng-repeat:
from django.core import serializers
from django.utils import simplejson
def json(request):
all_objects = list(Message.objects.all())
to_json = serializers.serialize('json', all_objects)
return HttpResponse(to_json, mimetype='application/json')
Now on to my question,
I'm not sure if I'm having an Angular issue or pure JavaScript issue. I have an Angular controller called testjson which calls that Django view above which then successfully returns a JSON object like this:
[
{
"pk":1,
"model":"chatfeed.message",
"fields":{
"body":"hey everyone",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:29:27Z"
}
},
{
"pk":2,
"model":"chatfeed.message",
"fields":{
"body":"How's it going?",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:32:05Z"
}
},
{
"pk":3,
"model":"chatfeed.message",
"fields":{
"body":"So what's going on right now",
"chat_feed":"Events",
"likes":0,
"author_obj":1,
"parent_channel":2,
"pub_date":"2014-03-18T23:32:33Z"
}
},
{
"pk":4,
"model":"chatfeed.message",
"fields":{
"body":"Going pretty well actually",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:32:55Z"
}
}
]
And so I would just like to grab the body of a particular chat_feed to be printed in Angular JS using Angular's ng-repeat to get something like this if I wanted all chat messages from chat_feed "Dating":
<div ng-controller="testjson" ng-click="getJSON()">
<ul ng-model="chatfeed">
<li ng-repeat="post in chatfeed">{$ post $}</li>
</ul>
</div>
So in order to get the ng-repeat to work, I believe. I would have to loop through the raw JSON object, grab the 'body' string from each index and store them into an array so that's what I did:
app.controller("testjson", function($scope, $http)
{
$scope.getJSON = function()
{
var JSONObject = $http.get('http://domfa.de/testjson/').success(function(data)
{
$scope.totalfeed = data.length;
chatarray = new Array();
for (var i=0; i < data.length; i++)
{
if (data[i].fields.chat_feed == $scope.currentFeed)
{
chatarray[i] = data[i].fields.chat_feed;
}
}
console.log(chatarray);
$scope.chatfeed = chatarray;
});
}
});
So after all that, my console.log seems to be returning the proper array just fine with the "body"s from the correct chat_feed. Console.log() is doing what I want it to do and the array it prints is properly formatted with perfect syntax, but as for the HTML which calls the ng-repeat="post in chatfeed" angular function it doesn't seem to print anything at all unless I physically copy and past the array console.log() prints out and replace ng-model="chatfeed" with a hardcoded array the console.log() generates for me with no problems using ng-init="['hows it going?', 'hey everyone']".
You are calling getJSON to populate chatfeed when the div is clicked. I wasn't able to trigger getJSON because I couldn't see where to click. So, I added some text to the div:
<div ng-controller="MainCtrl" ng-click="getJSON()">click me!
<ul>
<li ng-repeat="post in chatfeed">{{ post }}</li>
</ul>
</div>
When I clicked the div, I got an error message regarding duplicates in ng-repeat. If currentFeed = 'Dating', then there are 3 matching chat posts with the 'Dating' chat_feed. To allow for the duplicates, I added a tracking expression:
<li ng-repeat="post in chatfeed track by $index">{{ post }}</li>
But then, the list only displayed 'Dating' 3 times. You want the messages to be displayed - not the category. So, I changed the getJSON to add body instead of chat_feed to chatarray:
$scope.chatarray.push($scope.data[i].fields.body)
After making this change, the tracking expression is no long necessary because the body of each chat is unique.
Here is the plunker demo with the final adjustments: http://plnkr.co/edit/J4PtDpeRHO8TVItUnHJw?p=preview

I'm getting a "newItem() was not passed an identity for the new item" error while trying to add a new item to a JSON store

I've seen other posts in this site regarding the same issue and I've tried the solutions given. I've also visited the links that may offer a solution but I'm still stuck with the same error.
I'm using DOJO and something as simple as this won't even work
myStore.newItem({id: 'test', otherfield: 'otherinfohere'});
myStore.save();
Supposedly the "newItem() was not passed an identity for the new item" error appears when you haven't provided an identifier for the new item, which i have.
The whole purpose of this (Just in case anyone can provide a good idea or has done something similar before) is that i want to create a data grid that shows info from a particular store. The problem is, that in that store all the items may not have the same structure. For instance:
I may have a store that looks like this
{identifier: 'id',
label: 'name',
items: [
{ id:'1', name:'Ecuador', capital:'Quito' },
{ id:'2', name:'Egypt', capital:'Cairo' },
{ id:'3', name:'El Salvador', capital:'San Salvador' , additionalField: 'otherinfohere'},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', additionalField: 'otherinfohere'},
]}
This is possible because I'm the one constructing the store in a Spring Controller (I'm also using the Spring Framework) from information I have locally stored in a Berkeley DB. So what i need is a data grid with a dynamic layout because I don't want blank spaces to show in the view in the rows with lesser amount of fields, and i need to show all the info in the store at the same time, but i don't know how to do this.
I thought of doing it by creating a simple layout of only 1 field. In it I would load data from a store i create dynamically at runtime. The data in the store would be composed of HTML combined with the values coming from the original store so I could obtain something like this, which is inside an attribute of a JavaScript Object and let the browser parse it for me:
<div><span>id: originalID </span>....</div>
This of course is a simple example, the html layout i'm looking for is far more complicated, but i think that passing it as a string to an object might do the trick.
The problem is that i don't even know if that idea will work because i get that error whenever i try to add values to my secondary store.
rdb.modules.monitor.historicStore.fetch({onComplete: function(items, request){
for (var i = 0; i < items.length; i++){
var item = items[i];
var obj = new Object();
obj.id = rdb.modules.monitor.historicStore.getValue(item, "id");;
var html = "<div><span>";
html += rdb.modules.monitor.historicStore.getValue(item, "sql");
html += "</span></div>";
obj.html = html;
myStore.store.newItem(obj);
}
}});
In this context "historicStore" refers to the JSON store that has the values that i need to convert and add to "myStore" after i added some HTML.
I hope you got the main idea of what I'm trying to do. If anyone can help me we either of these problems i would really appreciate it. Thanks in advance
For the issue regarding store:-
"id" is mandatory for a store, if it is going to be used for a grid(datagrid, EnhancedGrid, etc. whatever). The items are handled only on basis of "id" attribute by the grid data structures.
Usually, id can be a loop variable/ auto incrementation, to avoid any cases like you have said. Before adding the store to the grid, ensure that all items have the id attribute. You can write a function which will loop through each item and check for this, else add an auto-incrementing value for the id attribute of that item.

Categories

Resources