You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
5 Hrs
5 Min
33 Seg

Crea tu propio miniframework: MiniVue

8/37
Resources

How to create our own mini framework?

Creating a mini framework can seem like an overwhelming task at first, especially if you're new to programming. However, by breaking the process into manageable steps and understanding how the key components work, you can build your own simple framework inspired by one like Vue.js. This mini framework will focus particularly on reactivity and data handling through proxies and custom directives.

What is the structure of our mini framework?

To begin with, we must understand the basic structure that our framework will adopt. Taking inspiration from Vue.js, we will keep a syntax that includes a data function that returns an object with all the necessary information for the application. Our goal is to create custom directives, such as pText and pModel, to handle how the data is displayed in the HTML.

  1. Create a framework file: The first step will be to create a .js file where we will develop all our framework code. For example, we will name this file platzi.js.

  2. Declare a global variable: We need a global variable to act as the core of our application. This variable, called Platzi, will contain the special rules and syntax of our mini framework.

  3. Define basic functions and classes:

    • createApp: Core function that will start the application and return a new instance of a class called PlatziReactive.
    • Directives: pText and pModel functions will be created to handle how the data interacts with the DOM.

How do we implement reactivity?

Reactivity is a key concept that allows changes in the data to be automatically reflected in the user interface (UI). In our framework, we will implement this feature using Reflect and Proxy.

Constructor and options

In the constructor of our reactive class, we will pass a set of options that includes the application data. Through these options, we will define an origin for our data (similar to data in Vue.js).

class PlatziReactive { constructor(options) { this.origin = options.data(); } // Other functions}

How do we assemble our application in the HTML?

To mount our application in the HTML, we will implement a mount function. This function will select all the elements containing the pText directive and apply the corresponding function to update the text in the DOM.

mount() { const elements = document.querySelectorAll('[p-text]'); elements.forEach(element => { const propertyName = element.getAttribute('p-text'); this.updateText(element, this.origin, propertyName); }); });}

What is the purpose of directives?

Directives are functions that allow you to bind and manipulate data directly in HTML. Our pText directive will take care of mapping the element's innerText to the property specified in the application's data.

function pText(element, dataTarget, propertyName) { element.innerText = dataTarget[propertyName];}

What's next in the evolution of the framework?

Up to this point, we have managed to create a solid foundation for an application that can handle data reactively with the help of proxies. However, this data source is not yet automatically responsive to changes. In future implementations, we will delve into how to convert this source to something more dynamic using proxies, creating a more fluid and efficient interaction between the application logic and its representation in the UI.

Putting together your own mini framework is not only a practical programming exercise, but also gives you valuable insight into the inner workings of popular frameworks. As you gain more experience, you can expand this base with more complex functions to suit your specific needs. Don't stop here and keep building and innovating!

Contributions 15

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

En este caso, simplemente se crea un objeto que va a retornar todos los métodos que necesitamos de nuestro mini framework, mediante el destructuring de JavaScript, en el index.html, estamos llamando al método createApp(), dicho método está dentro del objeto Platzi (Por eso usamos el destructuring al importar la fucnión en el index.html)
.
El mount es quien se encarga de pintar todo en el documento, mediante el querySlectorAll (recuerden que aquí funcionan los selectores de CSS) es como seleccionamos a todos los elementos que tengan el atributo p-text, en CSS al poner algo entre corchetes hace referencia a que va a seleccionar por atributos, por eso encerramos entre corchetes el [p-text], el asterisco es para decir que puede ser cualquier etiqueta, aunque realmente podríamos prescindir de él.
.
Por último, con getAttribute obtenemos el valor de dicho atributo, y el valor de ese atributo va a ser el nombre de la propiedad que esté dentro del objeto que retorna data() porque es el valor que queremos enlazar. Simplemente con el innerText metemos ese nombre. 👀
.
Iré creando commits en mi repositorio por si quieren ir viendo el código de cada clase:

https://github.com/RetaxMaster/mini-vue/tree/3ae74210698d150317999adb96b1b252f6551ed4

Ojala Samuel hubiera aumentado el tamaño del texto ya que para las personas con dos monitores es super sencillo ponerlo en pantalla completa y se ve bien pero con una sola pantalla lo normal es poner a un lado el video y a otro el codigo para poder escribir mientras samuel escribe pero es casi imposible ver la letra y toca detenerse y poner el video en pantalla completa para debuggear typos

God! Creo que me acaba de explotar el cerebro. Así como cuando crees que sabes JS y BOOM! Aprendes una cosa superloca y cool. Personalmente me tomo un buen rato entender la función pText(…) especialmente por los parámetros que recibe.
Excelente clase! Muchas gracias Samuel!

El curso se ve bien pero cada vez me molesta más que es casi imposible ver las letras en el video

con el query selector busca a todo lo que tenga p-text para recorrerlo cada uno y ejecutar la funcion que le inserta texto de acuerdo al target(data), y nombre (message)

En resumen, el ejercicio lo que hace es: 1\. Instanciar una clase JS y pasarle un obj con atributos: valor (Informacion De Origen que deseamos aisgnar al DOM). 2\. Dentro de la clase se estructura la misma con sus propiedades privadas y sus métodos. 3\. El método Mount(): Realiza un recorrido por todos los elementos DOM que tengan el atributo "p-text" y sobre cada uno llama a una funcion para setear la data del objeto OrigenData enviado. 4\. La funcion pText: recibe el elemento dom al que se le va asignar el texto, la fuente de la data enviada por nosotros y el nombre de la propiedad de este ultimo objeto, asignando asi al span p-text:"message" el valor el obj origen{ propiedad: valor. Nota: Para el entendimiento del código, pos escritura, es muy importante usar nomenclatura que oriente al lector, por ejemplo: pText debió haber sido configurada como setText por ejemplo, asi sabiamos que es una funcion de seteo, igual que sus parametros: (Elemento, ObjOrigenInfo, PropiedadNombre), esto facilitaria al estudiante una mejor comprensión. Salu2

Tremendo, Sam! sos un crac!

Igualmente, el profe debió haber hecho uso de CTRL + "+" sobre el VSCode para aprovechar mejor el espacio de trabajo grabado para el curso.

Es complicado entender este tema y el profesor no ayuda a hacerlo más fácil, hay que dejarle estos temas complicados a quienes tengan una buena vocación de enseñanza.

Gracias, muy buena explicación

PREGUNTA: como hago para usar el comando
npx http-server .

después q ya lo instale. es decir, para q cada vez q vaya a montar el servidor no tener q instalarlo de nuevo

Wow, es como ver la creación de Vue JS, qué interesante 😮

  pText(el, target, name) {
    el.innerText = target[name];
  }
elemento.innerText = objeto[propiedad];

target = {message:"Hola Vue" }
name = "message" 

Buenas, a mi no me funcionaba el ejemplo porque nadie está llamando al método mount(), no se si es cosa de mi navegador o algo así, lo solucioné añadiendo la llamda en el constructor:

constructor(options) {
    this.origen = options.data()
    this.mount()
}

Vue

class VueReactive{
    constructor(options){
        this.origen = options.data();
    }

    mount(){
        document.querySelectorAll("*[v-text]").forEach(el =>{
            this.vText(el, this.origen, el.getAttribute("v-text"))
        })
    }

    vText(el, target, name){
        el.innerText = target[name];
    }
    
    vModel(){}
}

var Vue = {
    createApp(options){
        return new VueReactive(options);
    }
};